Gus Sabina Gus Sabina - 25 days ago 10
JSON Question

Accessing attributes named as numbers

I 'm working in node.js and I have to parse the following object;

{ state:
{
desired: { '1': '0', '151': '2', hdr: [Object] },
reported: { '1': '0', '151': '2', hdr: [Object] }
}
}


I can access values like;

state.desired

state.desired.hdr[0]

but how can I access the attribute/value '1':'0' or '151':'2' ?

If I try like;

state.desired.151
or
state.desired.'151'

I get error...

Thanks
Gus

Answer Source

Use state.desired['151'] or state['desired']['151'];

If you want to get the value from an object where key is number or special character then, use this format: obj['key']

i.e

let myObj = { "1": "foo", "-" : "bar" } console.log(myObj['1']); // foo console.log(myObj['-']); // bar