I have two objects similar to this:
let data = [[
{
10: {key1: 1, key2: 2, key3: 3},
11: {key1: 1, key2: 2, key3: 3},
12: {key1: 1, key2: 2, key3: 3},
},
{},
{}
],
[
{
10: {key1: 1, key2: 2, key3: 3},
11: {key1: 1, key2: 2, key3: 3},
12: {key1: 1, key2: 2, key3: 3},
},
{},
{}
]]
I wanna create a new object and sum every value of each key. Like this:
let newData = [
{
10: {key1: 2, key2: 4, key3: 6},
11: {key1: 2, key2: 4, key3: 6},
12: {key1: 2, key2: 4, key3: 6},
},
{},
{}
]
Each object has three object in them. In these three objects, there is 45 keys, each of them has a object with three keys/values.
I can't find any good solution to sum every value.
My current solution is that I first loop thru data
:
let count = 0;
let count2 = 0;
for(let ob of data){
for(let child in ob[0]){
keyOne = ob[0][child].keyOne;
keyTwo = ob[0][child].keyTwo;
keyThree = ob[0][child].keyThree;
keyFour = ob[0][child].keyFour;
if(count < 45) {
newData[0][count].keyOne += keyOne;
newData[0][count].keyTwo += gkeyTwop;
newData[0][count].keyThree += keyThree;
newData[0][count].keyFour += keyFour;
} else {
newData[0][count2].keyOne += keyOne;
newData[0][count2].keyTwo += keyTwo;
newData[0][count2].keyThree += keyThree;
newData[0][count2].keyFour += keyFour;
count2++;
}
count++;
}
In the worst case, data got three objects with 45 keys each. Then I must do this three times. This seems really bad. There must be a better way. Tips?
via mintermasher
No comments:
Post a Comment