[英]Intersection of an array with a deeply nested object in javascript
I want to include all the keys of an object present in an array and discard the rest, For eg, 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.我希望我的结果对象仅包含来自
arr
的键,无论是直接键还是深度嵌套。 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, {}));
You could filter the entries and check if the (nested) objects contains a wanted key.您可以过滤条目并检查(嵌套)对象是否包含想要的键。
const hasKey = object => object && typeof object === 'object' && (keys.some(k => k in object) || Object.values(object).some(hasKey)), keys = ['apple', 'milk', 'bread', 'coke'], data = { apple: { category: 'fruit' }, banana: { category: 'fruit' }, potato: { category: 'vegetable' }, dairy: { milk: { type: 'A2' } }, bakery: { bread: { type: 'brown' } }, beverage: { cold_drink: { coke: { type: 'diet' } } } }, result = Object.fromEntries(Object .entries(data) .filter(([k, v]) => hasKey({ [k]: v })) ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.