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
You are using
product.attributes.map
andattribute.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
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.