我从 ajax 调用返回了这个 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}
]
}
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;
});
});
});
但我收到 TypeError: invalid 'in' operand a
错误。
获得我需要的东西的最佳方式是什么?
最佳答案
使用减少
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
甚至更短
obj.datasets.reduce( ( a, b ) => a + b.data.reduce( ( c, d ) => c + d , 0) , 0 );
演示
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 );
关于javascript - 在 javascript 或 jquery 中迭代多级对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47926771/