简体   繁体   English

根据Javascript中数组内对象数组的条件进行过滤

[英]filter based in criteria of an array of objects inside an array in Javascript

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.我只想过滤具有等于 true 的选定项的元素。 I try this:我试试这个:

const columnsWithSelectedItems = colmunsWithItemsToFilter.filter((columnWithItems) => {
    return columnWithItems.items.filter( item => item.selectedItem === true)
  })

but it return all elements.但它返回所有元素。

Thank you.谢谢你。

Instead of filter the defaultColumnsWithItems, you should return the whole object with the condition for the items array.您应该返回带有 items 数组条件的整个对象,而不是过滤 defaultColumnsWithItems。

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.在这种情况下,我们使用 map 函数来返回我们的对象,对于 items 数组,我们使用 filter 函数来过滤每个 item 中的 selectedItem。

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

Try this尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM