Vitaliy Isikov
Vitaliy Isikov

Reputation: 3654

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?

Upvotes: 1

Views: 86

Answers (5)

Lycha
Lycha

Reputation: 10187

You can do this to get the object:

num = '205'
miscObject[num]

Upvotes: 0

Microfed
Microfed

Reputation: 2890

var miscObject = JSON.parse(your-JSON-object);    
var value = miscObject['205'].h

Upvotes: 0

riwalk
riwalk

Reputation: 14233

Object values can be accessed 2 ways--using the 'dot' notation as you mentioned, or by using []'s:

The following should work:

var result = miscObject["205"].h;

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385395

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

Upvotes: 5

JaredPar
JaredPar

Reputation: 755397

Use the member lookup syntax

var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;

Upvotes: 1

Related Questions