skip to Main Content

My json structure looks like something like this

products = [{
    id: ...
    name: ...
    attributes: [{
       name: 'color',
       attribute_values: [{ value: 'blue' }, { value: 'green' }]
    }]
}]

I have filteredColors which I’m getting from query params which is an array of colors like ['blue', 'green', ...]

I’m trying to filter my products list based on the filteredColors.
I tried something like this

const handleFilterColors = (product) => {
    return filteredColors.length > 0 ? filteredColors.includes(
        product.attributes.map((attribute) => {
            return attribute.attribute_values.map((value) => value.value)
    })) : true;
}

const filteredAndSortedProducts = products.filter(handleFilterColors)

But this is not working. Need some help in filtering out here.

2

Answers


  1. You are using product.attributes.map and attribute.attribute_values.map, both will return arrays and you’re passing that array to includes, that will always return false.

    You need to update the code to use some

    const handleFilterColors = (product) => {
    return filteredColors.length > 0
        ? product.attributes.some((attribute) =>
              attribute.attribute_values.some((value) =>
                  filteredColors.includes(value.value)
              )
          )
        : true; };
    
    Login or Signup to reply.
  2. You need to change your code to only return true for products that have at least one of the colors in the filteredColors
    array You can do this by using the some() method.

    const products = [{
      id: 1,
      name: "Product 1",
      attributes: [{
          name: "color",
          attribute_values: [{
              value: "blue"
          }]
      }]
    }, {
      id: 2,
      name: "Product 2",
      attributes: [{
          name: "color",
          attribute_values: [{
              value: "green"
          }]
      }]
    }, {
      id: 3,
      name: "Product 3",
      attributes: [{
          name: "color",
          attribute_values: [{
              value: "red"
          }]
      }]
    }];
    const handleFilterColors = (product) => {
      return filteredColors.some(color => {
          return product.attributes.some(attribute => {
              return attribute.attribute_values.some(value => {
                  return value.value === color;
              });
          });
      });
    }
    
    const filteredColors = ["blue", "green"];
    
    const filteredAndSortedProducts = products.filter(handleFilterColors);
    
    console.log(filteredAndSortedProducts);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search