I want to include all the keys of an object present in an array and discard the rest, For e.g., if I have an array,
const arr = ['apple', 'milk', 'bread', 'coke'];
and an object,
const dummy = {
apple: {
category: 'fruit'
},
banana: {
category: 'fruit'
},
potato: {
category: 'vegetable'
},
dairy: {
milk: {
type: 'A2'
}
},
bakery: {
bread: {
type: 'brown'
}
},
beverage: {
cold_drink: {
coke: {
type: 'diet'
},
beer: {
}
}
}
}
I want my resultant object to contain the keys from arr only, be it direct keys or deeply nested. So for above case, my resultant object will look like,
{
apple: {
category: 'fruit'
},
dairy: {
milk: {
type: 'A2'
}
},
bakery: {
bread: {
type: 'brown'
}
},
beverage: {
cold_drink: {
coke: {
type: 'diet'
},
beer: {}
}
}
}
I am trying to solve this via recursion, but not able to get the output correctly. Below is my code, could you please help me with where I am going wrong?
function fetchResultantObject(object, key, result) {
if(typeof object !== 'object')
return null;
for(let objKey in object) {
if(key.indexOf(objKey) > -1) {
result[objKey] = object[objKey];
} else {
result[objKey] = fetchValueByKey(object[objKey], key, result);
}
}
return result;
}
console.log(fetchResultantObject(dummy, arr, {}));