高效地计算多个对象的总和 d3.js

3

我有一个对象,类似于:

{
  [

      {  id: "AL01",
         list: [
                  { speed : 5
                    value : 10} , 
                  { speed : 7
                    value : 15}
               ]
     }, 
     {  id: "AB01",
        list: [
                { speed : 20
                  value : 1} , 
                { speed : 8
                  value : 10}
              ]
     }

 ]

}

and i would like to have this result like:

{[ {  id: "AL01", speed: 12, value: 25}, {  id: "AB01", speed: 28, value: 11}]}

我该如何高效地获取这个呢? 如果只运行一次map或forEach函数,是否有可能? 我想让每个对象仅执行一次。
2个回答

2
您的数据结构不正确。您需要在数据对象中为最外层数组设置一个属性。因此,可以按照以下方式操作:

var data = {groups: [ {id: "AL01", list: [{ speed : 5,  value : 10}, { speed : 7, value : 15}]}, {id: "AB01", list: [{ speed : 20, value : 1 }, { speed : 8, value : 10}]}]},
  result = {groups: data.groups.map(g => Object.assign({id: g.id},g.list.reduce((r,c) => ({speed : r.speed + c.speed, value : r.value + c.value}))))};
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
你需要更多循环才能得到结果。
基本上,先使用外部数组,然后迭代list并为键使用另一个数组。然后收集所有数据并返回具有新结构的新对象。

var array = [{ id: "AL01", list: [{ speed: 5, value: 10 }, { speed: 7, value: 15 }] }, { id: "AB01", list: [{ speed: 20, value: 1 }, { speed: 8, value: 10 }] }],
    result = array.map(function (a) {
        var temp = { id: a.id, speed: 0, value: 0 };
        a.list.forEach(function (b) {
            ['speed', 'value'].forEach(function (k) {
                temp[k] += b[k];
            });
        });
        return temp;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接