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);
-
you have to loop through them because I guess adam/bobby is not static. Something like data[i].x.TESTFredrik– Fredrik2011年05月15日 18:24:22 +00:00Commented May 15, 2011 at 18:24
4 Answers 4
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
x = "ADAM";
alert(data[0][x].TEST);
Comments
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
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
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;
}