fuzzii fuzzii - 1 year ago 72
JSON Question

How do I access a JSON property that is nested within an id, without hardcoding the id?

I'm trying to access a property of a JSON object using TypeScript. The JSON object is obtained from a server in this format:

"1111": {
"id": 1111,
"name": "NAME",
"available": 3,

This JSON object has property names that match my typescript class, used to deserialise the JSON object into this class.
I've been able to access a property is this way:

jsonObj['1111'].name //this correctly returns "NAME"

However, I would prefer to use the id of the JSON object as a variable, as opposed to hardcoding the id into the call to get the property. Is there a way to do something like this?

let idOfJsonObj = '1111'
jsonObj[idOfJsonObj].name //this implementation throws an error

Answer Source

Simply use:

let idOfJsonObj = 1111

Don't use quotes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download