我有类似的代码如下:
var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];
var reduced=temp.reduce(function (a,b) {
return a.y + b.y;
});
console.log(reduced) // returns NAN
Run Code Online (Sandbox Code Playgroud)
Nin*_*olz 21
您可以使用起始值并仅从数组中添加一个值.
var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];
var reduced = temp.reduce(function (r, a) {
return r + a.y;
// ^^^ use the last result without property
}, 0);
// ^^^ add a start value
console.log(reduced) // rRun Code Online (Sandbox Code Playgroud)
简短的解决方案:将集合映射到整数集合,并减少它
var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];
var reduced = temp
.map(function(obj) { return obj.y; })
.reduce(function(a, b) { return a + b; });
console.log(reduced);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3891 次 |
| 最近记录: |