问题
I have the following array named filters and try to filter it by selected items.
At the end I want to have all filters where a selected item is, but only with the selected items
let filters = [
{
id: 0,
name: 'property',
items: [
{
id: 0,
name: 'x',
isSelected: false
},
{
id: 1,
name: 'y',
isSelected: true
}
]
},
{
id: 1,
name: 'property2',
items: [
{
id: 0,
name: 'x',
isSelected: true
},
{
id: 1,
name: 'y',
isSelected: false
}
]
}
]
I want to get the following array at the end:
let filteredFilters = [
{
id: 0,
name: 'property',
items: [
{
id: 1,
name: 'y',
isSelected: true
}
]
},
{
id: 1,
name: 'property2',
items: [
{
id: 0,
name: 'x',
isSelected: true
}
]
}
]
I tried the following code, but it does not work.
let filteredFilters = filters.filter(filter => {
return filter.items.filter(item => {
return item.isSelected === true;
})
})
回答1:
You need map
+ filter
since you're dealing with a nested array:
let filters = [
{
id: 0,
name: 'property',
items: [
{
id: 0,
name: 'x',
isSelected: false
},
{
id: 1,
name: 'y',
isSelected: true
}
]
},
{
id: 1,
name: 'property2',
items: [
{
id: 0,
name: 'x',
isSelected: true
},
{
id: 1,
name: 'y',
isSelected: false
}
]
}
]
let filteredFilters =
filters.map(
({items, ...rest}) => ({...rest, items: items.filter(item => item.isSelected)})
)
.filter(x => x.items.length > 0);
console.log(filteredFilters);
来源:https://stackoverflow.com/questions/62056650/filter-array-in-array-and-get-only-the-filtered-items