I have this sample data and I wanted to filter it where the colors are less than 20 or equal to 20:
const data = [
{
colors: { green: 8 },
name: "Item1"
},
{
colors: { Black: 6, Green: 7 },
name: "Item2"
},
{
colors: { Green: 20, Yellow: 31, Pink: 36 },
name: "Item2"
},
{
colors: { Black: 39, Red: 21 },
name: "Item4"
}
];
I recreated this in codesandbox: https://codesandbox.io/s/magical-margulis-yy1moz?file=/src/App.js
I tried this:
const data = [{colors: { green: 8 },name: "Item1"},{colors: { Black: 6, Green: 7 },name: "Item2"},{colors: { Green: 20, Yellow: 31, Pink: 36 },name: "Item2"},{colors: { Black: 39, Red: 21 },name: "Item4"}];
const newData = data.filter((item) => {
return Object.entries(item.colors).filter((c) => c[1] < 20);
});
console.log(newData);
It does not correctly filter. I can still see all of the items even if they are more than 20
The expected output would be to show the filtered data:
Item1, green: 8
Item2, Black: 6, Green: 7,
Item3, Green: 20
>Solution :
You can filter on color value using array#filter and create a new colors object and push it in result using array#reduce.
const data = [ { colors: { green: 8 }, name: "Item1" }, { colors: { Black: 6, Green: 7 }, name: "Item2" }, { colors: { Green: 20, Yellow: 31, Pink: 36 }, name: "Item2" }, { colors: { Black: 39, Red: 21 }, name: "Item4" } ],
result = data.reduce((r, o) => {
const colors = Object.entries(o.colors).filter(([,val]) => val <= 20);
if(colors.length) {
r.push({ colors: Object.fromEntries(colors), name: o.name });
}
return r;
},[]);
console.log(result);