Here is the data that I am working with:
input1 =
[{
"201609": 5,
"201610": 7,
"201611": 9,
"201612": 10,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 3,
"201610": 6,
"201611": 9,
"201612": 8
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 1,
"201610": 2,
"201611": 3,
"201612": 5
"FY17": 6,
"careerLevel": "CL1"
},
{
"201609": 2,
"201610": 4,
"201611": 6,
"201612": 9
"FY17": 12,
"careerLevel": "CL2"
}
]
}]
}]
input2 =
[{
"201609": 4,
"201610": 8,
"201611": 12,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 9,
"201610": 2,
"201611": 7,
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 3,
"201610": 6,
"201611": 9,
"FY17": 18,
"careerLevel": "CL1"
},
{
"201609": 7,
"201610": 8,
"201611": 9,
"FY17": 24,
"careerLevel": "CL2"
}
]
}]
}]
output = input1 + input2.
The final output should be a sum of all the numeric values. Even if a key like "201612" does not match in both inputs, it should still be included in the output.
[{
"201609": 9,
"201610": 15,
"201611": 21,
"201612": 10,
"FY17": 48,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 12,
"201610": 8,
"201611": 16,
"201612": 8,
"FY17": 24,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 4,
"201610": 8,
"201611": 12,
"201612": 5,
"FY17": 24,
"careerLevel": "CL1"
},
{
"201609": 9,
"201610": 12,
"201611": 15,
"201612": 9,
"FY17": 36,
"careerLevel": "CL2"
}
]
}]
}]
This is my approach:
var output = [{}];
for(let i in input){
for (let key in input[i]){
if (output[0].hasOwnProperty(key)) {
output[0][key]+=input[i][key];
}else{
output[0][key]=input[i][key];
}
}
}
console.log(JSON.stringify(output)); // encountering errors
However, this method is not providing the desired outcome as it struggles to handle the hierarchical json structure depicted above.