我在实现嵌套数据过滤时遇到问题.我从API获得了此类数据:
const animals = {
bugs: ['ant', 'cricket'],
fish: ['shark', 'whale', 'tuna'],
mammals: ['cow', 'horse', 'sheep'],
birds: ['eagle', 'crow', 'parrot'],
predators: ['tiger', 'lion']
}
我必须使用此数组过滤它们:
我想要达到的结果是:
const filtered = {
fish: ['shark'],
mammals: ['cow', 'horse'],
birds: ['parrot'],
}
我try 过:
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'],
}
我仍然无法达到预期的效果,因为数组中的项目不会被添加,而是被替换.我被困在这里了.任何帮助都将不胜感激.谢谢