How can I retrive the value from closed JSON object?

Viewed 51

The response object looks like this: (this response is coming form the server)

               {
                   "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?

2 Answers
  1. Convert JSON to JS object - JSON.parse(jsonString)
  2. 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]}`)
  })
})

You can use a combination of JSON.parse and .map to get a flat array of "xyz"

const json = '{ "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" }] }';
const jobj = JSON.parse(json);
const xyzs = jobj.abc.map((a) => a.xyz);
console.log(xyzs);

Related