Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge the the two values of two objects that share a common key together and return it?

Write a function called mergeCounters which accepts two objects where all of the values are numbers and returns a new object with the total of both objects. The order of your returned object does not matter, as long as it contains the correct keys and values!

function mergeCounters (object1, object2) {
  var myObj = {};
  for (key in obj1) {
    for (key2 in obj2) {
      var val = myObj[key + key2];
    }
  }
  return myObj;
}

var obj1 = {a: 1, b:2, c:3};
var obj2 = {a: 3, b:6, c:7};
console.log(mergeCounters(obj1, obj2)); // {a:4, b:8, c:10}

var obj3 = {a: 1, c:3, d:5};
var obj4 = {a: 3, b:6, c:7, z:20};
console.log(mergeCounters(obj3, obj4)); // {a:4, b:6, c:10, d:5, z:20}
like image 454
Mark Rubio Avatar asked Nov 17 '25 08:11

Mark Rubio


1 Answers

You don't need a nested loop here since you can use the key to index/access the values from both objects. Since object1 may have more properties than object2 and vice versa, you can first merge all object properties from both object1 and object2 into a merged object using the spread syntax .... Once you have a merged object, you can iterate the keys of the object using for...in, and grab the key from both object1 and object2 to add to the new resulting object. One object may not have the other key, so you can default the value to 0 using || 0 if it doesn't exist.

See example below:

function mergeCounters (object1, object2) {
  const merged = {...object1, ...object2};
  const result = {};
  for(const key in merged) {
    result[key] = (object1[key] || 0) + (object2[key] || 0);
  }
  return result;
}

var obj1 = {a: 1, b:2, c:3};
var obj2 = {a: 3, b:6, c:7};
console.log(mergeCounters(obj1, obj2)); // {a:4, b:8, c:10}

var obj3 = {a: 1, c:3, d:5};
var obj4 = {a: 3, b:6, c:7, z:20};
console.log(mergeCounters(obj3, obj4)); // {a:4, b:6, c:10, d:5, z:20}
like image 92
Nick Parsons Avatar answered Nov 18 '25 23:11

Nick Parsons