简体   繁体   中英

How can I filter array items by object arrays in ReactJS?

I'm creating an application in React ES6, where I need to filter a list of products by category and type. I have a list of test product data as follows:

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

I need to filter the data by categories and type, using preset variables ie Cat 1 and Type 2.

I have the following code however I'm aware it's not functioning correctly as the categories and types are arrays within the objects.

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

How can I change this so it functions as requires? Any help would be much appreciated.

update this logic

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

Use includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const result = ProductData.filter(
  x => x.categories.includes(category) && x.types.includes(type)
);

 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"] } ]; const category = "Cat 1"; const type = "Type 2"; const result = ProductData.filter(x => x.categories.includes(category) && x.types.includes(type)); console.log(result);

You can use the .filter() and .includes methods:

const productData = {...}
const category = 'Cat 1'
const type = 'Type 2'

const results = productData.filter(el => el.categories.includes(category) && el. types.includes(type))

This should work as expected.

const results = ProductData.filter(item => item.categories.includes('Cat 1') && item.types.includes('Type 2'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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