我的输入:[ { date: '2019-11-20', deposits: 100 }, { date: '2019-11-20', deposits: 300 }, { date: '2019-11-21', deposits: 200 }, { date: '2019-11-21', deposits: 500 } ]预期输出:var Output=[ { date: '2019-11-20', deposits: 400 } , { date: '2019-11-21', deposits: 700 }]如果日期相同,我只需添加存款并在同一日期下仅显示一次。我如何在 NodeJS 中做到这一点?我试图以多种方式做到这一点,但我失败了。谁可以帮我这个事 ?
1 回答
qq_笑_17
TA贡献1818条经验 获得超7个赞
如果您可以使用库(lodash),那就更容易了。否则,您可以使用 Map 进行分组,例如:
const input = [
{ date: '2019-11-20', deposits: 100 },
{ date: '2019-11-20', deposits: 300 },
{ date: '2019-11-21', deposits: 200 },
{ date: '2019-11-21', deposits: 500 }
];
const m = new Map();
input.forEach(({ date, deposits }) => m.set(date, (m.get(date) || 0) + deposits));
// and if want to have it as an array, convert it back:
const output = [...m].map(([date, deposit]) => ({ date, deposit }));
console.log(output);
添加回答
举报
0/150
提交
取消