V
V
vladislav31012021-05-10 21:49:04
React
vladislav3101, 2021-05-10 21:49:04

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}]
 }
}

How can I filter products by key
promotion
from the filters object.
Of course, it would be easier if the filters were known to me and I just did something like this:
promotion: {
  isDiscountChecked: false,
  isFreeChecked: false 
}

const Products = ({products, filters}) => {
  return (
     <>
       {filters.promotion.isDiscountChecked && products.filter(item => item.isChecked === true).map(product => <div>...</div>)}
       // ....
    </>
  );
}

But how to solve this problem if I don't know the filters beforehand?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VladimirAsmo, 2021-05-11
@VladimirAsmo

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(...)}
    </>
  );
}

This solution will work if your products and filter.promotion agree on data types. Now you have porridge. products.discount stores a boolean and filter.promotion[0].value a string. In order to compare correctly, they must be of the same type, or decide which string values ​​you will mean true and which false.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question