I have a problem implementing filtering for nested data. I have this kind of data from API :
const animals = {
bugs: ['ant', 'cricket'],
fish: ['shark', 'whale', 'tuna'],
mammals: ['cow', 'horse', 'sheep'],
birds: ['eagle', 'crow', 'parrot'],
predators: ['tiger', 'lion']
}
I have to filter them with this array :
const data = ['shark', 'horse', 'cow', 'parrot']
The result I want to achieve :
const filtered = {
fish: ['shark'],
mammals: ['cow', 'horse'],
birds: ['parrot'],
}
I have tried :
filter.forEach((item) => {
for (let key in animals) {
let species = []
if (animals[key].includes(item)) {
filtered[key] = [...species, species]
}
}
})
and the result :
const filtered = {
fish: ['whale'],
mammals: ['cow',],
birds: ['parrot'],
}
I still can't achieve the desired outcome, because the items inside array will not be added but replaced. I'm stuck here. Any help will be really appreciated. Thanks !