javascript - 在 javascript 或 jquery 中迭代多级对象

标签 javascript jquery

我从 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/

相关文章:

Javascript 类变量作用域

jquery - 单击按钮从 DIV 复制文本

javascript - 使用希伯来数字自定义 <ol> 编号

javascript - 防止 VueJs 中浏览器 url 的位置更改

javascript - 使用 node.js 在值之间查询 DynamoDB

javascript - 更改前清理输入

javascript - 将事件处理程序附加到 Twitter Bootstrap 弹出窗口中的按钮

javascript - 如何调试鼠标移动

javascript - CSS 过渡高度变化不起作用

javascript - 将 Jest 文本覆盖记者输出到 .txt