0

I have this JSON data stored in variable result, now I want to access the value of result.metadata.data.s1[1].lily , however the key Lily is not known and it may change on server side, so I stored the key as a variable, like var key1 = "Lily". How to access the value with this var key1 ?

{
         "metadata":{

            "data":{
               "s1":[
                  {
                     "Lily":"chat",
                     "time":10
                  },
                  {
                     "Mancy":"chat1",
                     "time":10
                  },
                  {
                     "John":"chat2",
                     "time":10
                  }
               ],
               "s2":[
                  {
                     "Lan":"chat3",
                     "time":10
                  },
                  {
                     "Yoyo":"chat6",
                     "time":10
                  }
               ]
            }
         }

}
Blake
  • 7,367
  • 19
  • 54
  • 80

1 Answers1

1

If you always know it's the first item in the list, bracket notation should work fine.

result.metadata.data.s1[0][key1];

If you're not sure where it falls, then the [0] won't always be correct, and you'll have to iterate through all of the items in the result.metadata.data.s1 array to find it.

Your code above is getting the second item in the list, at index [1], and the key there is not "Lily", it's "Mancy".

Here's a codepen demo

nwalton
  • 2,033
  • 21
  • 22
  • `data.metadata.data.s1[0]` is an `object` not an `array`, you cant access the value this way – Blake Mar 06 '14 at 20:17
  • @Blake- Right, `data.metadata.data.s1` is the array. `data.metadata.data.s1[0]` is the first object in that array. It contains the "Lily" key. – nwalton Mar 06 '14 at 21:03
  • Working codepen added. Bracket notation seems to work fine, unless I've missed something. – nwalton Mar 06 '14 at 21:16
  • hmm, my mistake, why I have this impression that value in object can be accessed that way... never mind. – Blake Mar 06 '14 at 22:03