I’m looking to filter an array of objects that is within an array of objects. E.g. items within the nested array are filtered out but not items of the outer most array.
Here is a sample input array:
categories = [{
categoryName: 'Mammals',
items: [{
name: 'Dog',
power: '52',
},{
name: 'Bear',
power: '205',
},{
name: 'Mouse',
power: '7',
}]
},{
categoryName: 'Reptiles',
items: [{
name: 'Alligator',
power: '230',
},{
name: 'Turtle',
power: '39',
}]
}];
Desired output: power greater than 50:
output = [{
categoryName: 'Mammals',
items: [{
name: 'Dog',
power: '52',
},{
name: 'Bear',
power: '205',
}]
},{
categoryName: 'Reptiles',
items: [{
name: 'Alligator',
power: '230',
}]
}];
I have attempted to use the filter function as such, but it outputs the full original array:
output = categories.filter((category) => category.items.power > 50)
I also tried using .some like this, same issue:
output = categories.filter((category) => category.items.some((item) => item.power > 50))
2
Answers
Use
map()
to iterate over the categories, then usefilter()
to filter the items in each category.Use
map
andfilter
: