阵列与JavaScript中深嵌套对象的交点
我想在数组中包括存在的对象的所有键,然后丢弃其余的对象, 对于Eg,如果我有一个 array
const arr = ['apple', 'milk', 'bread', 'coke'];
和对象,
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: {
}
}
}
}
我希望我的结果对象包含来自arr 仅是直接密钥还是深嵌套。因此,对于上述情况,我所产生的对象看起来像是,
{
apple: {
category: 'fruit'
},
dairy: {
milk: {
type: 'A2'
}
},
bakery: {
bread: {
type: 'brown'
}
},
beverage: {
cold_drink: {
coke: {
type: 'diet'
},
beer: {}
}
}
}
我试图通过递归来解决此问题,但无法正确获取输出。以下是我的代码,您能帮助我解决我的意思吗?
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, {}));
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, {}));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以过滤条目,并检查(嵌套)对象是否包含想要的键。
You could filter the entries and check if the (nested) objects contains a wanted key.