Reputation: 739
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 i.e. 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.
Upvotes: 0
Views: 67
Reputation: 307
This should work as expected.
const results = ProductData.filter(item => item.categories.includes('Cat 1') && item.types.includes('Type 2'))
Upvotes: 0
Reputation: 779
update this logic
var results = ProductData.filter(item => {
return item.categories.includes(category) && item.types.includes(type)
})
Upvotes: 1
Reputation: 170
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))
Upvotes: 0
Reputation: 15186
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);
Upvotes: 0