Issue
I have this array :
defaultColumnsWithItems = [
{
column: 'Contrie', items: [
{ id: 1, label: 'USA', selectedItem: true },
{ id: 2, label: 'FRANCE', selectedItem: false },
{ id: 2, label: 'MAROC', selectedItem: false }
]
},
{
column: 'Categorie', items:
[
{ id: 0, label: 'Alimentaion', selectedItem: true },
{ id: 1, label: 'ricolage', selectedItem: false },
{ id: 2, label: 'Literie', selectedItem: true },
{ id: 3, label: 'Menage', selectedItem: false },
]
}
];
I want to filter only the elements with selected item withe value equal to true. I try this:
const columnsWithSelectedItems = colmunsWithItemsToFilter.filter((columnWithItems) => {
return columnWithItems.items.filter( item => item.selectedItem === true)
})
but it return all elements.
Thank you.
Solution
Instead of filter the defaultColumnsWithItems, you should return the whole object with the condition for the items array.
In this scenario, we use the map function to return our object and for items array, we use the filter function to filter selectedItem in each item.
const defaultColumnsWithItems = [
{
column: 'Contrie', items: [
{ id: 1, label: 'USA', selectedItem: true },
{ id: 2, label: 'FRANCE', selectedItem: false },
{ id: 2, label: 'MAROC', selectedItem: false }
]
},
{
column: 'Categorie', items:
[
{ id: 0, label: 'Alimentaion', selectedItem: true },
{ id: 1, label: 'ricolage', selectedItem: false },
{ id: 2, label: 'Literie', selectedItem: true },
{ id: 3, label: 'Menage', selectedItem: false },
]
}
]
const items = defaultColumnsWithItems.map(el => {
return {
column: el.column,
items: el.items.filter(i => i.selectedItem)
}
})
console.log('items: ', items);
Answered By - Mahdi Rezazadeh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.