0

I have json in the following format.

  [{"custId":7,"emailId":"raju.allen1888@gmail.com","facebookId":"","twitterId":"","mobilePhone":"","landPhone":"","firstName":"Allen","lastName":""},{"custId":8,"emailId":"raju@gmail.com","facebookId":"","twitterId":"","mobilePhone":"","landPhone":"","firstName":"Emanuel","lastName":""}]

i have a dropdown list with all the keys, if i choose a key, for e.g emailId, i need to get the emailId from the json.

it works fine when i give like this,

      for(i in data){
       alert(data[i].emailId);
      }

when i get the value from the dropdown in a variable and try to use it like the following its giving me error as undefined.

     var key = $('#dropdownvalue').val(); //emailId as value from the dropdown

     for(i in data){
       alert(data[i].key);
      }

how to solve this, to select the value for the key selected through dropdown.

Raju.allen
  • 341
  • 2
  • 9
  • 21
  • 1
    Note, what you have is NOT a JSON (at least if you can iterate through it!) but a JavaScript array object, containing other JS objects. See the JSON tag wiki for the difference. – Benjamin Gruenbaum Jun 07 '13 at 08:41

1 Answers1

4

Use bracket notation to access the property with a dynamic name :

alert(data[i][key]);

This means go to the object data[i] and access a property whose name is the string value of what's contained in key

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758