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?

4
  • 1
    First of all, it's not xx[0].name, it's xx.name. Or, more correct, xx["name"]. Commented May 31, 2010 at 11:00
  • 3
    @Felix: why is xx["name"] "more correct" than xx.name? Commented May 31, 2010 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. Commented May 31, 2010 at 11:20
  • 3
    That makes it more flexible, not more correct. It is also less efficient since you have to create a string. Commented May 31, 2010 at 11:42

3 Answers 3

2
for (i in xx) {
    if (xx[i] == "alx") {
        // i is the key
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

what if the other day value is not alx and something else.
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
    }
}

3 Comments

sorry, may b qs is not very clear, but is there a way to retrieve key without even considering the corresponding value
@Wondering, how will you identify what key you want then?
@Wondering, pay attention to the comment in that code. // i is the key
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.