首页 > 解决方案 > 如何在 ReactJS 中按对象数组过滤数组项?

问题描述

我正在 React ES6 中创建一个应用程序,我需要在其中按类别和类型过滤产品列表。我有一个测试产品数据列表如下:

const ProductData = [
  {
    id: 1,
    name: 'Product 1',
    categories: ['Cat 1', 'Cat 2'],
    types: ['Type 1', 'Type 3']
  },
  {
    id: 2,
    name: 'Product 2',
    categories: ['Cat 2', 'Cat 3'],
    types: ['Type 1', 'Type 2']
  },
  {
    id: 3,
    name: 'Product 3',
    categories: ['Cat 1', 'Cat 3'],
    types: ['Type 2', 'Type 3']
  },
];

我需要使用预设变量(即 Cat 1 和 Type 2)按类别和类型过滤数据。

我有以下代码,但是我知道它无法正常运行,因为类别和类型是对象中的数组。

const category = 'Cat 1';
const type = 'Type 2';

// need to filter here by both the category and the type
var results=_.filter(ProductData,function(item){
  return item.types.indexOf({type})>-1;
});

如何更改它以使其按需要运行?任何帮助将非常感激。

标签: javascriptreactjsecmascript-6

解决方案


更新这个逻辑

var results = ProductData.filter(item => {
  return item.categories.includes(category) && item.types.includes(type)
})

推荐阅读