I am trying to filter an array of objects (my product data) with an object that has an array of values (my filter criteria state)
Here is what my filter criteria state data structure looks like:
{
productname: []
designer: []
sizes: []
category: []
}
and this is an example of how my product data object looks like :
[
{
"id": "10",
"productName": "M NRG BH Jacket",
"designer": "NIKE",
"category": "outerwear",
"sizes": ["XS", "S", "M", "L", "XL"],
"color": "limestone",
"description": "CACT.US CORP...",
"price": 400,
"img": [
"m-nrg-jacket-nike",
"m-nrg-jacket-nike2",
"m-nrg-jacket-nike3",
"m-nrg-jacket-nike4"
]
}
...
]
And this is my current attempt trying to use the reduce function and iterating through each of my filterCriteria's to set state for my displayedProducts component
const [displayedProducts, setDisplayedProducts] = useState(productData);
const filter = () => {
let updatedDisplayedProducts = [];
let count = 0;
for (const filterKey in filterCriteria) {
const currFilter = filterCriteria[filterKey];
productData.reduce((accum, curr) => {
console.log(currFilter);
console.log(curr[filterKey]);
if (!accum) {
return productData;
} else if (filterKey === "sizes") {
if (filterCriteria[filterKey].includes(curr[filterKey])) {
updatedDisplayedProducts.push(curr);
}
} else if (currFilter.includes(curr[filterKey].toUpperCase())) {
updatedDisplayedProducts.push(curr);
}
console.log(updatedDisplayedProducts);
setDisplayedProducts(updatedDisplayedProducts);
}, []);
}
};
I've tried some other solutions but I always came across an issue where I was essentially nesting too many for loops and it was mutating my state somehow. Any help is greatly appreciated!