Get values from object if the name of the object is stored as a variable?

I have a JSON object return with the following format:

"miscObject": {
    "205": [
        {
            "h": "Foo",
            "l": "Bar"
        }
        ]
    }

miscObject contains somewhere over 1500 entries, each named incrementally.

How can I get to the values of 'miscObject.205.h' and 'miscObject.205.l' if I have "205" stored in variable without having to loop through all of the objects inside miscObject?

Answers


It seems that you're talking about Javascript objects rather than a JSON string.

x[y] and x.y are mostly interchangeable when accessing properties of Javascript objects, with the distinction that y in the former may be an expression.

Take advantage of this to solve your problem, like so:

var num = '205';
console.log(miscObject[num].l);
//                    ^^^^^
//                      \
//                     instead of `.num`, which wouldn't be the same as
//                       `num` is not the literal name of the property

Need Your Help

Google custom search API - sorting / filter

google-search google-search-api

Is there anyway to filter the results by page title tag or certain meta tags...

JSONP Help (No jQuery)

ajax json jsonp javascript

I'm trying hard here to figure out how to do a JSONP request, but everywhere I look for reference material is all jQuery examples. I can read the jQuery source, but I wanted a clean and simple exam...