Consider you have a complex deeply nested object with 15 - 20 levels and you want to query a certain node inside it based on a field and modify a particular attribute. How can we achieve it?
Following example is contrived and the object is not as complex as my case and not as deep so please don't suggest something like obj[phoneNumbers][0].number = somethingNew
I'm using a library called jsonpath in below example to query a specific node and get its value using jsonpath expression.
var jp = require("jsonpath");
const obj = {
firstName: "John",
lastName: "doe",
age: 26,
address: {
streetAddress: "naist street",
city: "Nara",
postalCode: "630-0192"
},
phoneNumbers: [
{
type: "iPhone",
number: "0123-4567-8888"
},
{
type: "home",
number: "0123-4567-8910"
}
]
};
const number = jp.query(obj, "$.phoneNumbers[0].number");
console.log(number);
// outputs: [ '0123-4567-8888' ]
Thank you.