I need to group by id and sum, but I need a new object for each result:
let data = [
{"id":"2018", "name":"test", "total":1200},
{"id":"2019", "name":"wath", "total":1500},
{"id":"2019", "name":"wath", "total":1800},
{"id":"2020", "name":"zooi", "total":1000},
]
I have this code that returns just one object with the result
let result = data.reduce(function (r, o) {
(r[o.id])?
r[o.id] += o.total:
r[o.id] = o.total;
return r;
});
But I need some like this:
[
{"id":"2018", "name":"test", "total":1200},
{"id":"2019", "name":"wath", "total":2300},
{"id":"2020", "name":"zooi", "total":1000},
]
How can I do it?
let data =[
{"id":"2018", "name":"test", "total":1200},
{"id":"2019", "name":"wath", "total":1500},
{"id":"2019", "name":"wath", "total":1800},
{"id":"2020", "name":"zooi", "total":1000},
];
let map = data.reduce((prev, next) =>{
if (next.id in prev) {
prev[next.id].total += next.total;
} else {
prev[next.id] = next;
}
return prev;
}, {});
let result = Object.keys(map).map(id => map[id]);
console.log(result);
You can try this:
const result = Object.values(data.reduce((r, o) => (r[o.id]
? (r[o.id].total += o.total)
: (r[o.id] = {...o}), r), {}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With