views:

68

answers:

3

I have a JSON like:

  var xx = {'name':'alx','age':12};

Now I can read the value of name which is 'alx' as xx[0].name, but how should I retrieve value of 'name' itself? By that, I mean how can I fetch the key at run time?

+2  A: 
for (i in xx) {
    if (xx[i] == "alx") {
        // i is the key
    }
}
Victor Stanciu
what if the other day value is not alx and something else.
Wondering
+1  A: 

modified Code (from Victor) taking into account that you might want to look for any other possible string

var search_object = "string_to_look_for";
for (i in xx) {
    if (xx[i] == search_object) {
        // i is the key 
        alert(i+" is the key!!!"); // alert, to make clear which one
    }
}
Thariama
sorry, may b qs is not very clear, but is there a way to retrieve key without even considering the corresponding value
Wondering
@Wondering, how will you identify what key you want then?
J-P
@Wondering, pay attention to the comment in that code. // i is the key
Sean Hogan
A: 

You are looking for associative arrays in Javascript. A quick google search suggests the following:

Read this page http://www.quirksmode.org/js/associative.html

and especially this section http://www.quirksmode.org/js/associative.html#link5

Sean Hogan