I'd say the easiest option would be an optional chaining operator or something, but I believe the right way to do this is something like JSONPath.
There might be other libraries (e.g. like jsonpath one or jsonpath-plus) which allows you to do the same.
JSONPath is XPath for JSON.
JSON Example:
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
And this is how you can get the authors of all books in the store using JSONPath expression:
$.store.book[*].author
You can use it in JavaScript:
const o = { /*...*/ }, // the 'store' JSON object from above
res1 = jsonPath(o, "$..author").toJSONString(); // all authors JSONPath expression
res2 = jsonPath(o, "$..author", {resultType:"PATH"}).toJSONString();