我从jj调用返回这个json:
{"datasets":[
{"data":[0,0,2,0,1,0,0,0,0,0,5,2], "service_ID": 1},
{"data":[0,0,0,0,0,0,0,0,0,0,1,3], "service_ID": 2},
{"data":[0,0,0,0,0,0,0,0,0,0,0,2], "service_ID": 3},
{"data":[0,0,0,0,0,0,0,0,0,0,0,4], "service_ID": 4},
{"data":[0,0,0,0,0,0,0,0,0,0,0,1], "service_ID": 5}
]
}
Run Code Online (Sandbox Code Playgroud)
data对象内的每个元素都是一月份的值,从1月到12月(12个元素的数组)
我需要循环内部datasets以获取data对象内的每个值并获得总和,在此示例中:2+1+5+2+1+3+2+4+1 = 21
我试过了
var total = 0;
$.each(datasets, function(index, data) {
$.each(data, function(index, month) {
$.each(month, function(index, value) {
total = total + value;
});
});
});
Run Code Online (Sandbox Code Playgroud)
但我得到TypeError: invalid 'in' operand a错误.
得到我需要的最好的方法是什么?
使用 reduce
obj.datasets.reduce( function( a, b ){ //
return a + b.data.reduce( (c, d) => c + d , 0); // 0 is the accumulator for data property of each item in the array
} , 0); //0 is the accumulator which is the final output
Run Code Online (Sandbox Code Playgroud)
甚至更短
obj.datasets.reduce( ( a, b ) => a + b.data.reduce( ( c, d ) => c + d , 0) , 0 );
Run Code Online (Sandbox Code Playgroud)
演示
var obj = {"datasets":[
{"data":[0,0,2,0,1,0,0,0,0,0,5,2], "service_ID": 1},
{"data":[0,0,0,0,0,0,0,0,0,0,1,3], "service_ID": 2},
{"data":[0,0,0,0,0,0,0,0,0,0,0,2], "service_ID": 3},
{"data":[0,0,0,0,0,0,0,0,0,0,0,4], "service_ID": 4},
{"data":[0,0,0,0,0,0,0,0,0,0,0,1], "service_ID": 5}
]
};
var output = obj.datasets.reduce( function( a, b ){
return a + b.data.reduce( (c, d) => c + d , 0);
} , 0);
console.log( output );Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |