Suppose there is a very long and nested JSON and you need to find a specific key value( "domain": "pack" inside that JSON and return the object containing that key value pair. The path to that key is something like item.items.offerings.item.items.offers.item.items.offers.domain
The tricky part here is that both items and offers are arrays with multiple objects and all of those objects contain item. So we need to search in each object inside items and offers.
function findDomain(obj) {
if (obj && typeof obj === 'object') {
if (obj.domain === 'pack') {
return obj;
}
let found = false;
let result;
for (const key in obj) {
if (obj.hasOwnProperty(key) && !found) {
const value = obj[key];
const childResult = findDomain(value);
if (childResult) {
found = true;
result = childResult;
}
}
}
return result;
}
return null;
}
const pack = findDomain(a);
console.log(pack);
//a is the object
I have used recursive method which is working fine, but i am not sure if its the best solution. Is there a better way to solve this without using any library.