按date字段分组聚合对象数组并对相同字段求和的实现方法
实现方案
你可以通过临时分组映射的方式实现该需求,无需硬编码除date外的其他字段,后续新增数值字段也能自动适配:
const data = [ {date: '8 - 2021', 'a20 - plan1': 20, 'b70 - plan1': 10, 'c30 - plan1': 5}, {date: '9 - 2021', 'a20 - plan1': 60, 'b70 - plan1': 70, 'c30 - plan1': 20}, {date: '8 - 2021', 'a20 - plan1': 10, 'b70 - plan1': 5, 'c30 - plan1': 5}, {date: '9 - 2021', 'a20 - plan1': 5, 'b70 - plan1': 5, 'c30 - plan1': 5} ]; // 临时分组映射,key为date值 const groupMap = {}; data.forEach(item => { const dateKey = item.date; // 首次遇到该日期时初始化分组项 if (!groupMap[dateKey]) { groupMap[dateKey] = { date: dateKey }; } // 遍历所有属性累加数值,跳过date字段 Object.keys(item).forEach(key => { if (key !== 'date') { groupMap[dateKey][key] = (groupMap[dateKey][key] || 0) + item[key]; } }); }); // 转成数组得到最终结果 const result = Object.values(groupMap); console.log(result);
如果偏好更简洁的写法,也可以用reduce实现,逻辑完全一致:
const result = Object.values( data.reduce((acc, cur) => { const dateKey = cur.date; if (!acc[dateKey]) acc[dateKey] = { date: dateKey }; Object.keys(cur).forEach(key => { if (key !== 'date') acc[dateKey][key] = (acc[dateKey][key] || 0) + cur[key]; }) return acc; }, {}) );
内容的提问来源于stack exchange,提问作者Adrian Iordache
相关产品推荐
相关产品推荐

