15

What I mean by that is say I have JSON data as such:

[{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]

and I want to do something like this:

var x = "ADAM";
alert(data.x.TEST);
1
  • you have to loop through them because I guess adam/bobby is not static. Something like data[i].x.TEST Commented May 15, 2011 at 18:24

4 Answers 4

24
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
    x = "ADAM";

alert(data[0][x].TEST);

http://jsfiddle.net/n0nick/UWR9y/

Sign up to request clarification or add additional context in comments.

Comments

5

Since objects in javascripts are handled just like hashmaps (or associative arrays) you can just do data['adam'].TEST just like you could do data.adam.TEST. If you have a variable index, just go with the [] notation.

var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]
alert(data[0].ADAM.TEST);
alert(data[0]['ADAM'].TEST)

if you just do

var data = {"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}};

you could access it using data.ADAM.TEST and data['ADAM'].TEST

Comments

0

That won't work as you're setting x to be a string object, no accessing the value from your array:

alert(data[0]["ADAM"].TEST);

Comments

0
 var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
 x = "ADAM";

alert(data[x].TEST);

This is what worked for me. This way you can pass in a variable to the function and avoid repeating you code.

function yourFunction(varName, elementName){
//json GET code setup
document.getElementById(elementName).innerHTML = data[varName].key1 + " " + data.[varName].key2;
}

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.