To sum up the values of two objects with key-value pairs, you can iterate through the keys of both objects, add the corresponding values, and store the results in a new object. Here’s a simple JavaScript example to illustrate this:
const obj1 = {
a: 10,
b: 20,
c: 30
};
const obj2 = {
a: 5,
b: 15,
d: 25
};
function sumValues(object1, object2) {
const result = {};
// Add values from obj1
for (const key in object1) {
if (object1.hasOwnProperty(key)) {
result[key] = object1[key];
}
}
// Add values from obj2
for (const key in object2) {
if (object2.hasOwnProperty(key)) {
if (result.hasOwnProperty(key)) {
result[key] += object2[key];
} else {
result[key] = object2[key];
}
}
}
return result;
}
const summedObject = sumValues(obj1, obj2);
console.log(summedObject);