Skip to content Skip to sidebar Skip to footer

How Do I Access A Json Object Using A Javascript Variable

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);

Solution 1:

vardata = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
    x = "ADAM";

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

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

Solution 2:

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.

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

if you just do

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

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

Solution 3:

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);

Solution 4:

vardata = [{"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.

functionyourFunction(varName, elementName){
//json GET code setupdocument.getElementById(elementName).innerHTML = data[varName].key1 + " " + data.[varName].key2;
}

Post a Comment for "How Do I Access A Json Object Using A Javascript Variable"