更新时间:2023-02-05 13:36:52
你可以试试这个:
const 结果 = Object.values(data.reduce((r, o) => (r[o.id]?(r[o.id].total += o.total): (r[o.id] = {...o}), r), {}));
i need help with this, i need 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 return 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},
]
any suggestion?, thanks
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), {}));