The response object looks like this:
{
"abc": [{
"xyz": "INFO 1",
"pqr": "INFO 2"
},
{
"xyz": "INFO 3",
"pqr": "INFO 4"
}]
}
The expected value from this object
xyz, INFO 1
xyz, INFO 3
Could you help me to retrieve this value from the object?
>Solution :
- Convert JSON to JS object –
JSON.parse(jsonString) - Use standard dot notation and bracket notation to retrieve the values (e.g.
JSobject.abc[0].xyz)
const object = {
"abc": [{
"xyz": "INFO 1",
"pqr": "INFO 2"
},
{
"xyz": "INFO 3",
"pqr": "INFO 4"
}
]
}
console.log(object.abc[0].xyz)
If you know the structure of the JSON you’re getting you can also iterate through it to get all the data at once:
const object = {
"abc": [{
"xyz": "INFO 1",
"pqr": "INFO 2"
},
{
"xyz": "INFO 3",
"pqr": "INFO 4"
}
]
}
object.abc.forEach(o => {
Object.keys(o).forEach(p => {
console.log(`${p}, ${o[p]}`)
})
})