我正在 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']
},
];
我需要使用预设变量(即类别 1 和类型 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;
});
如何更改它以使其按要求运行?任何帮助将非常感激。
最佳答案
更新此逻辑
var results = ProductData.filter(item => {
return item.categories.includes(category) && item.types.includes(type)
})
关于javascript - 如何在 ReactJS 中通过对象数组过滤数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61227120/