javascript - 如何在 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;
});
如何更改它以使其按需要运行?任何帮助将非常感激。
解决方案
更新这个逻辑
var results = ProductData.filter(item => {
return item.categories.includes(category) && item.types.includes(type)
})
推荐阅读
- javascript - 将特定参数传递给函数
- flutter - 如何将动态 url 从 DataProvider 发送到 PDF Flutter
- python - 在条件下将大数据框拆分为多个
- android - 如何在 Android 中从 liferay 6 登录屏幕中获取身份验证令牌,以便将其与 REST API 调用一起使用?
- python - 构建包失败
- android - 微光布局 api 19
- php - 从 laravel 中的条带 php 包中模拟条带类
- python - 3 个数字中最大的一个代码不适用于特定数字
- powershell - How to recursively append to file name in powershell?
- dart - 带有包装数组的测试流