简体   繁体   中英

When referring to a JSONObject in javascript, how do I refer to it using a variable (rather than the name itself)?

I looked up all the other StackOverflow posts for this, but none seemed to work. I'll post my code below:

$.getJSON('bugs.json', function (data) {
    for ( var observer = 1; observer <= data.numObservers; observer++) {
        var observerName = "num" + observer;

        var specs = ['congestion', 'bloodflow'];
        for ( var spec in specs) {
            var tableCode = "<br><table id=\"" + observer + specs[spec] + "\" > <thead> <tr> <th>" + specs[spec] + "</th> <th id=\"value\">Value</th> <th id=\"time\">Time</th></tr>";
            $('body').append(tableCode);
            var observerObj = data[observerName] + " kaka " + data.num1.congestion.values[1];

            var selectedSpec = specs[spec];
            for (var i = 0; i < observerObj[selectedSpec].values.length; i++) {
                tr = $('<tr/>');
                tr.append ("<td> Name </td>");
                tr.append("<td>" + data[observerName][spec].values[i] + "</td>");
                tr.append("<td>" + data[observerName][spec].times[i] + "</td>");
                $('#'+observer+spec).append(tr);                
            }
        }
    }
});

When using the browser console log, I get an error that observerObj[selectedSpec] doesn't work.

Thanks in advance for your help.

Edit : the exact console error is:

TypeError: observerObj[selectedSpec] is undefined

var observerObj = data[observerName] + " kaka " + data.num1.congestion.values[1];

If I am reading this correctly, observerObj is a string - not an array or object. So observerObj[selectedSpec] would not exist.

You're trying to iterate over an array as an object.

var specs = ['congestion', 'bloodflow'];
for ( var spec in specs) {

This is trying to iterate for every property on specs not each object inside of it. You want to do something like this...

var specs = ['congestion', 'bloodflow'];
for ( var i = 0; i < specs.length; i++) {

Then access each item via specs[i]

Hope this helps!

MDN Article about for ... in should help too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM