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?

Donal Fellows
  • 126,337
  • 18
  • 137
  • 204
Wondering
  • 4,820
  • 21
  • 70
  • 90
  • 1
    First of all, it's not `xx[0].name`, it's `xx.name`. Or, more correct, `xx["name"]`. – Felix May 31 '10 at 11:00
  • 3
    @Felix: why is xx["name"] "more correct" than xx.name? – Victor Stanciu May 31 '10 at 11:05
  • @Victor: because you can have keys with special characters, for example `xx["some key"]`. This is valid, yet you can't access it like `xx.some key`. That's why I prefer to always use the `xx["name"]` notation. – Felix May 31 '10 at 11:20
  • 3
    That makes it more flexible, not more correct. It is also less efficient since you have to create a string. – Quentin May 31 '10 at 11:42

3 Answers3

2
for (i in xx) {
    if (xx[i] == "alx") {
        // i is the key
    }
}
Victor Stanciu
  • 11,197
  • 3
  • 25
  • 34
1

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
  • 49,060
  • 11
  • 131
  • 155
0

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
  • 2,854
  • 23
  • 22