Effective use of multiple d3.js object sums
I have an object like:
{
[
{ 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 get a result like this:
{[ { id: "AL01", speed: 12, value: 25}, { id: "AB01", speed: 28, value: 11}]}
How can I get this efficiently? If you can only run the map or forEach functions once? I'm interested in what happens only once per object.
+3
source to share
2 answers
Your data structure is wrong. You must have a property for the outermost array in the data object. Accordingly, you can do the following:
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; }
+2
source to share
You will need a few more loops to get the result.
Basically an external array, then iterate list
and use another array for the keys. Then collect all the data and return a new object with a new structure.
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; }
+1
source to share