开发者

How do I access a JSON object using a javascript variable

开发者 https://www.devze.com 2023-03-06 13:54 出处:网络
What I mean by that is say I have JSON data as such: [{\"ADAM\":{\"TEST\":1}, \"BOBBY\":{\"TEST\":2}}]

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";
a开发者_StackOverflow中文版lert(data.x.TEST);


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

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

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


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


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


 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消