Answer the question
In order to leave comments, you need to log in
How to filter json products in this case?
Products, filters come from the server and the result is:
const initialState = {
categories: [{id: 1, name: 'Категория-1'}],
products: [
{id: 1, title: 'Продукт-1', price: 1, discount: true, free: false},
{id: 2, title: 'Продукт-2', price: 2, discount: false, free: false},
{id: 3, title: 'Продукт-3', price: 5, discount: true, free: true},
],
filters: {
categories: [{categoryId: 1, isChecked: true}],
promotion: [{id: 1, name: 'discount', value: 'Скидка', isChecked: false}, {id: 2, name: 'free', value: 'Бесплатно', isChecked: false}]
}
}
promotionfrom the filters object.
promotion: {
isDiscountChecked: false,
isFreeChecked: false
}
const Products = ({products, filters}) => {
return (
<>
{filters.promotion.isDiscountChecked && products.filter(item => item.isChecked === true).map(product => <div>...</div>)}
// ....
</>
);
}
Answer the question
In order to leave comments, you need to log in
If I understood the problem correctly, then it can be done like this.
const Products = ({products, filters}) => {
const filteredProducts = products.filter((product) => {
const currentFilter = filters.promotion.find((filter) => product.id === filter.id);
if (!currentFilter) return true; // or do something else
if (!product.hasOwnProperty(currentFilter.name)) return true;
return product[currentFilter.name] === currentFilter.value;
});
return (
<>
{filteredProducts.map(...)}
</>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question