Reputation: 3654
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
Reputation: 2890
var miscObject = JSON.parse(your-JSON-object);
var value = miscObject['205'].h
Upvotes: 0
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
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
Reputation: 755397
Use the member lookup syntax
var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;
Upvotes: 1