I am currently in the process of learning JavaScript and had a quick question on a project i am working on. Currently If i want to merge a few Objects, add the values together if the keys match or append the parent obj if a key is not already existing, i can do the following:
var test1 = {
a: 12,
b: 8,
c: 17
};
var test2 = {
a: 22,
b: 8,
c: 9
};
var test3 = {
a: 33,
b: 23,
c: 1,
d: 2,
e: 9
};
function sumObjectsByKey(...objs) {
return objs.reduce((a, b) => {
for (let k in b) {
if (b.hasOwnProperty(k))
a[k] = (a[k] || 0) + b[k]
}
return a;
}, {});
console.log("endresult" + " " + sumObjectsByKey(test1, test2, test3));
This seems to work just fine when there is just ONE value. ex: a: 22
So this is where my issue comes in. What if the objects look like this:
var test1 = {
testSystem: {crit: "1", high: "0", med: "1", low: "22"}
testSystem1: {crit: "1", high: "0", med: "1", low: "22"}
testSystem2: {crit: "1", high: "0", med: "1", low: "22"}
testSystem3: {crit: "1", high: "0", med: "1", low: "22"}
};
var test2 = {
testSystem: {crit: "19", high: "305", med: "21", low: "212"}
4testSystem1: {crit: "111", high: "10", med: "31", low: "62"}
testSystem2: {crit: "21", high: "3", med: "11", low: "232"}
testSystem4: {crit: "13", high: "40", med: "15", low: "22"}
testSystem7: {crit: "21", high: "3", med: "112", low: "32"}
};
var test3 = {
testSystem5: {crit: "1", high: "0", med: "122", low: "122"}
testSystem2: {crit: "2", high: "6", med: "1", low: "222"}
testSystem3: {crit: "6", high: "0", med: "12", low: "212"}
testSystem4: {crit: "4", high: "8", med: "11", low: "2"}
};
how can i modify the above code to iterate through to do the same as above? Any explanation or help would be greatly appreciated. thanks.