[英]Reduce array of object to totals by property object
我正在寻找一种智能的ES6方法来将对象数组减少为按属性对象的总数。
对于样本数据:
const src = [{mon:1,tue:0,wed:3,thu:5,fri:7,sat:0,sun:4}, {mon:5,tue:3,wed:2,thu:0,fri:1,sat:0,sun:6}];
以下代码:
const res = src.reduce((totals,item) => Object.keys(item).forEach(weekday => totals[weekday] += item[weekday]),{})
抛出错误:
未捕获的TypeError:无法读取未定义的属性'mon'
即使使用{mon:0, tue:0 ...}
而不是{}
初始化reduce
。
有非循环解决方案吗?
ps期望输出是一个对象,其中每个属性是该属性的数组对象的总和,例如{mon:6, tue:3, wed:5, thu:5, fri:8, sat:0, sun:10}
in我的情况
修改后需要返回totals
:
const src = [{mon:1,tue:0,wed:3,thu:5,fri:7,sat:0,sun:4}, {mon:5,tue:3,wed:2,thu:0,fri:1,sat:0,sun:6}]; const res = src.reduce((totals, item) => { Object.keys(item).forEach(weekday => totals[weekday] = (totals[weekday] || 0) + item[weekday]); return totals; }, {}); console.log(res);
您需要将totals
作为累加器返回以进行reduce
。
如果你在对象的所有日子里总是如此,并且你不介意改变第一个对象,你可以在没有起始对象的情况下工作。
const src = [{ mon: 1, tue: 0, wed: 3, thu: 5, fri: 7, sat: 0, sun: 4 }, { mon: 5, tue: 3, wed: 2, thu: 0, fri: 1, sat: 0, sun: 6 }], res = src.reduce((totals, item) => (Object.keys(item).forEach(d => totals[d] += item[d]), totals)); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.