www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 26

Thread: retrieve value from multi-dim associative array using only one string as the key

  1. #1
    Join Date
    Jan 2008
    Posts
    273

    retrieve value from multi-dim associative array using only one string as the key

    Hi All

    Lets assume the following object

    Code:
    var x = {
                   y: {
                        z: 10
                   }
    } ;
    Next, I need to retrieve the value '10', but the only thing I have is one string as a key
    For example (this doesn't work):

    Code:
         var str = '[y][z]' ; // or 'y.z'??
         alert(x[str]) ; // should alert 10
    Can this be done using a single string as input for x ?

    cheers

    UPDATE: a solution which comes close to what I was looking for is
    Code:
          var str = "x['y']['z']" ;
          alert(eval(str));
    Last edited by jeanluca; 07-20-2011 at 06:11 AM.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,380

    Lightbulb

    Have you tried...
    Code:
    <!DOC HTML>
    <html>
    <head>
    <title> Untitled </title>
    <script type="text/javascript">
    var x = {
          y: {
             z: 10
          }
    };
    alert(x.y.z);
    </script>
    
    </head>
    <body>
    
    </body>
    </html>

  3. #3
    Join Date
    Jan 2008
    Posts
    273
    Sure, that works like a charm, but thats not the issue here.
    You don't know about 'y.z' because they're stored in a string! So you could do

    Code:
        var str = 'y.z' ;
        var items = 'y.z'.split() ;
        alert( x[items[0]][items[1]] ;
    But that just doesn't look right (BTW: the code above was not tested)

    cheers

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,380

    Arrow

    I guess I'm confused then...
    How would you know 'y' or 'z' is available if you do not know the structure of 'x'?

    BTW: One reason the code would not work because a ')' is missing at the end of the alert.

  5. #5
    Join Date
    Jan 2008
    Posts
    273
    thats right, but you got the idea!

    Think of it as a user provided you (through a text input field) y.z

  6. #6
    Join Date
    Aug 2007
    Posts
    3,767
    Well, you could eval it, but I wouldn't recommend that if the user is providing it, so instead, I'd parse the string, splitting it at ".", and then finding the corresponding element.

    Something like:
    Code:
    var x = {y:{z:10}};
    var a = "y.z";
    a = a.split(".");
    var r = x;
    for (var i = 0; i < a.length; i++) {
    r = r[a[i]];
    }
    Last edited by Declan1991; 07-20-2011 at 01:05 PM.
    Great wit and madness are near allied, and fine a line their bounds divide.

  7. #7
    Join Date
    Jan 2008
    Posts
    273
    ok. I noticed that you can do the same with new Function. Is this basically the same thing ?

  8. #8
    Join Date
    Aug 2007
    Posts
    3,767
    You mean, new Function("x"+userString) where userString = ".y.z"? That's the same as eval, and a bad idea if you are taking the string from the user. If at all possible, avoid eval, new Function and setTimeout/Interval with strings.
    Great wit and madness are near allied, and fine a line their bounds divide.

  9. #9
    Join Date
    Jan 2008
    Posts
    273
    ok, thanks!

  10. #10
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,380

    Question Why?

    Quote Originally Posted by Declan1991 View Post
    Well, you could eval it, but I wouldn't recommend that if the user is providing it, so instead, I'd parse the string, splitting it at ".", and then finding the corresponding element.

    Something like:
    Code:
    var x = {y:{z:10}};
    var a = "y.z";
    a = a.split(".");
    var r = x;
    for (var i = 0; i < a.length; i++) {
    r = r[a[i]];
    }
    I'm still a bit confused as to where you would use something like this.

    Why would you need a loop when you already have been told there is 'y.x'?
    Code:
    <script type="text/javascript">
     var x = {y:{z:10}};
     var a = "y.z";
     a = a.split(".");
     alert(x[a[0]][a[1]]+' is same as '+x.y.z);
    </script>

  11. #11
    Join Date
    Aug 2007
    Posts
    3,767
    Quote Originally Posted by JMRKER View Post
    Why would you need a loop when you already have been told there is 'y.x'?
    I've a penchant for generalisation! Can't help it.
    Great wit and madness are near allied, and fine a line their bounds divide.

  12. #12
    Join Date
    Jan 2008
    Posts
    273
    exactly, suppose you don't know anything about the structure of x and someone (or a webservice) tells to get a value out of the variable and the path is 'm.n.o.p'

  13. #13
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,380

    Question

    Quote Originally Posted by jeanluca View Post
    exactly, suppose you don't know anything about the structure of x and someone (or a webservice) tells to get a value out of the variable and the path is 'm.n.o.p'
    I'm not questioning the file structure.
    I'm not questioning the fact that the creator would give you 'm.n.o.p' to access a variable.

    I'm questioning why you would need to split the 'm.n.o.p' into an array
    when you could use the arrayX.m.n.o.p access directly.

  14. #14
    Join Date
    Dec 2008
    Posts
    488
    I think I see what you're looking for. You need quotes around y and z when used in brackets, otherwise you're telling the javascript to eval a variable. Also, x must be in a string since the brackets are in strings, and these two must be concatenated:

    Code:
    var str = '["y"]["z"]',
          x = {
              y : {
                  z : 10
              }
          };
    
    alert(eval('x' + str)) ; // should alert 10
    Or using the x.y.z structure:

    Code:
    var str = '.' + 'y.z', //notice I add a leading dot
          x = {
              y : {
                  z : 10
              }
          };
    
    alert(eval('x' + str)) ; // should alert 10
    This assumes you know the name of x and aren't using variables created on the fly or chosen through conditions.
    Last edited by jamesbcox1980; 07-21-2011 at 10:46 AM.

  15. #15
    Join Date
    Aug 2007
    Posts
    3,767
    Quote Originally Posted by JMRKER View Post
    I'm questioning why you would need to split the 'm.n.o.p' into an array
    when you could use the arrayX.m.n.o.p access directly.
    I thought the whole point was that the m.n.o.p was coming from the user, and I wouldn't be in an awful rush to eval stuff that comes straight from the user, when it could be done like I did it which gives plenty of opportunity for validation too.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles