I have a javascript array object from a database input like this:
[{ date: '2021-09-15', type: 'cats', value: 4 },
{ date: '2021-09-15', type: 'dogs', value: 5 },
{ date: '2021-09-16', type: 'cats', value: 1 },
{ date: '2021-09-16', type: 'dogs', value: 4 }]
And I need an output like this:
[{ date: '2021-09-15', cats: 4, dogs: 5 },
{ date: '2021-09-16', cats: 1, dogs: 4 }]
I am trying to use the reduce function by this way, however, I can't get it to work (it's grouping the data but not modifying it thus, they are left with a single value)
const data = [
{ date: '2021-09-15', type: 'cats', value: 4 },
{ date: '2021-09-15', type: 'dogs', value: 5 },
{ date: '2021-09-16', type: 'cats', value: 1 },
{ date: '2021-09-16', type: 'dogs', value: 4 }
]
const groups = data.reduce((groups, item) => {
const key = item[item.date];
if (!groups[key]) {
groups[item.date] = []
}
if (item.type == "cats") {
item.cats = item.value;
} else if (item.type == "dogs") {
item.dogs = item.value;
}
groups[item.date].push(item);
return groups;
}, {});
console.log(groups)
.as-console-wrapper { max-height: 100% !important; }