1

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?

5 Answers 5

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

Use the member lookup syntax

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

Comments

0

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;

Comments

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

Comments

0

You can do this to get the object:

num = '205'
miscObject[num]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.