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

阿卜杜勒

我有这个数组:

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 },
    ]
}

];

我只想过滤具有等于 true 的选定项的元素。我试试这个:

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

但它返回所有元素。

谢谢你。

马赫迪·雷扎扎德

您应该返回带有 items 数组条件的整个对象,而不是过滤 defaultColumnsWithItems。

在这种情况下,我们使用 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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

根据javascript中的键名过滤对象数组

遍历对象数组并根据多个条件对其进行过滤

根据条件过滤JavaScript数组

过滤javascript中数组内对象内的数组

如何根据Ruby中的条件哈希过滤对象数组?

根据Typescript中对象嵌套数组的值进行过滤

根据对象数组中的属性过滤数组

JavaScript 根据值对对象数组进行排序(条件排序)

您如何根据条件过滤对象数组

根据子条件过滤嵌套的对象数组

根据多种条件过滤对象的JSON数组

根据对象的嵌套数组进行过滤

根据多值对象过滤JavaScript对象数组

如何根据数组内的对象数组过滤数组

如何使用javascript根据数组中的键进行过滤?

根据条件从数组中删除对象数组

根据另一个对象数组中的条件过滤对象数组

如何过滤对象数组并根据对象在数组中显示的次数进行排序

Java流,根据对象中的条件进行过滤,将值设置为字符串和数组

RestAssured - JsonPath 根据过滤条件从对象数组中过滤匹配对象的属性

如何在 iOS Swift 中的嵌套数组(对多关系)中根据条件过滤对象数组

根据输入值/ javascript过滤数组对象

JavaScript根据属性值过滤对象数组

过滤对象javascript中的数组

在 Javascript 中过滤对象数组

如何根据嵌套数组中的值过滤带有对象的数组并对其进行计数

如何根据数组中的元素进行过滤?

javascript过滤数组内部对象中的数组

根据javascript中的另一个对象数组过滤对象数组