多个对象的总和有效d3.js

时间:2017-05-27 09:06:55

标签: javascript arrays d3.js nested sum

我有一个像这样的对象:

.thumbnail {
  width: 100%;
  height: 150px;
  background-size: cover;
  background-repeat: no-repeat;
}

我希望得到这样的结果:

<div id="minetn" class="thumbnail" style="background-image: url('http://2.bp.blogspot.com/-uK7LaDSSyFE/Vhi2nrCu5iI/AAAAAAAAGE0/2Ht-q9oYO24/s1600/Bitcoin-mining.jpg')"></div>

我怎样才能有效地获得这个? 如果只能运行一次函数map或forEach? 我想知道每件物品只能运行一次的东西。

2 个答案:

答案 0 :(得分:2)

您的数据结构不正确。您必须拥有数据对象中最外层数组的属性。因此,可以做如下的事情;

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要更多循环才能获得结果。

基本上是外部数组,然后迭代allDots1并使用另一个数组作为键。然后收集所有数据并返回一个具有新结构的新对象。

&#13;
&#13;
list
&#13;
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);
&#13;
&#13;
&#13;