Home > Mobile >  filter based in criteria of an array of objects inside an array in Javascript
filter based in criteria of an array of objects inside an array in Javascript

Time:06-13

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.

CodePudding user response:

Try this

defaultColumnsWithItems.map(function(ComparisonResult) {
  ComparisonResult.items = ComparisonResult.items.filter(x => x.selectedItem);
  return ComparisonResult;
});

CodePudding user response:

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);

  • Related