在javascript或jquery中迭代多级对象

Giu*_*ini 0 javascript jquery

我从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错误.

得到我需要的最好的方法是什么?

gur*_*372 5

使用 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)

  • 您还应该添加OP实现的错误 (2认同)