How do I access a JSON object using a javascript variable

后端 未结 4 1476
傲寒
傲寒 2020-12-29 09:48

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

相关标签:
4条回答
  • 2020-12-29 10:05

    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

    0 讨论(0)
  • 2020-12-29 10:11

    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);
    
    0 讨论(0)
  • 2020-12-29 10:13
     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 讨论(0)
  • 2020-12-29 10:17
    var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
        x = "ADAM";
    
    alert(data[0][x].TEST);
    

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

    0 讨论(0)
提交回复
热议问题