我在对嵌套数据实现过滤时遇到问题。我有来自 API 的这种数据:
const animals = {
bugs: ['ant', 'cricket'],
fish: ['shark', 'whale', 'tuna'],
mammals: ['cow', 'horse', 'sheep'],
birds: ['eagle', 'crow', 'parrot'],
predators: ['tiger', 'lion']
}
我必须用这个数组过滤它们:
const data = ['鲨鱼', '马', '牛', '鹦鹉']
我想要达到的结果:
const filtered = {
fish: ['shark'],
mammals: ['cow', 'horse'],
birds: ['parrot'],
}
我试过了:
filter.forEach((item) => {
for (let key in animals) {
let species = []
if (animals[key].includes(item)) {
filtered[key] = [...species, species]
}
}
})
结果:
const filtered = {
fish: ['whale'],
mammals: ['cow',],
birds: ['parrot'],
}
我还是达不到预期的结果,因为数组里面的项目不会被添加而是被替换。我被困在这里了。任何帮助将不胜感激。谢谢!
最佳答案
您可以重建对象的条目。
const
animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] },
data = ['shark', 'horse', 'cow', 'parrot'],
result = Object.fromEntries(Object
.entries(animals)
.flatMap(([k, a]) => {
a = a.filter(v => data.includes(v));
return a.length
? [[k, a]]
: []
})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于Javascript - 过滤包含数组的对象,其值来自另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72683502/