Reputation: 109
I have a 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 have this result like:
{[ { id: "AL01", speed: 12, value: 25}, { id: "AB01", speed: 28, value: 11}]}
How can i get this efficiently? If is it possible to run only one time the functions map or forEach? I'm wondering something which go by only one time per each object.
Upvotes: 3
Views: 123
Reputation: 26191
Your data structure is not correct. You have to have a property for the outermost array in the data object. Accordingly one can do as follows;
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; }
Upvotes: 2
Reputation: 386680
You need some more loops to get the result.
Basically the outer array, then iterate list
and use another array for the keys. Then collect all 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; }
Upvotes: 1