Home > other >  I'm confused about this statement, Object.entries
I'm confused about this statement, Object.entries

Time:11-16

useEffect(() => {
  cat &&
    setFilteredProducts(
      products.filter((item) =>
        Object.entries(filters).every(([key, value]) =>
          item[key].includes(value)
        )
      )
    );
}, [products, cat, filters]);

I've been watching the video, over and over again but I can't seem to understand it properly, can somebody help me explain this line by line? I've get the point about "cat &&" but the rest confuses me.

CodePudding user response:

Going through the above code line by line:

I am assuming you have a state variable with a setter function setFilteredProducts and two arrays products and filters, each having objects as values.

We are setting values in the state variable from the filtered values stored in the products variable.

Object.entries simply returns an array, where each item is an array with its first value as keys and the second value as the corresponding value, every is another function that applies on the array returned by the Object.entries function

The every function takes in a callback function as an argument, which tests whether all elements in the array pass the test implemented by the callback.

In this case, the test implemented is item[key].includes(value), which tests whether each iterated element(an object) in the products array has an array corresponding to key with value in it.

You can refer to Object.entries here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Array.prototype.every: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

Array.prototype.filter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Array.prototype.includes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

  • Related