0

Hey so I'm working on a JS project, and I came across an issue where I am trying to add/merge 2 objects together. So basically, there is a base object:

{age: 0,
 lvl: 123,
 xp: 321}

So we have this, and I have another object coming in with

{age: 12,
 lvl: 21}

The result I want is

{age: 12,
 lvl: 144,
 xp: 321}

But that could be easily achieved with just individual property addition. However, I want to come to a point where I don't know what properties the object has, yet they are still added. Oh and the property type will for sure be a number. Any ideas?

Edit: Ok, I see I mis worded some stuff. What I meant by me not knowing which properties it has, I meant that I know that the object may have one-all properties of the first object, just that I don't know which ones the second one has and does have.

Shady Goat
  • 60
  • 1
  • 9

2 Answers2

3

Loop through the keys of the second object and add them to the first:

const first = {
    age: 0,
    lvl: 123,
    xp: 321
};
const second = {
    age: 12,
    lvl: 21
};
for (const key in second) {
    first[key] = (first[key] || 0) + second[key];
}
console.log(first);

Read more about for...in loops here.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • @3limin4t0r pretty important thing to take into account though, given that OP said `However, I want to come to a point where I don't know what properties the object has, yet they are still added.`. I think it's safe to assume that we don't know for sure what ANY properties are in the first or second objects, and that he'd still want a sensible behaviour for those scenarios where the second object has properties not in the first object. – TKoL Dec 07 '20 at 17:40
  • It's an easy fix by replacing the line in the loop with `first[key] = (first[key] || 0) + second[key]` (or `??` instead of `||` for newer js versions). – Aplet123 Dec 07 '20 at 17:41
  • Yeah sorry I did mis word that. In the new edit I specified that the properties of the second object are in the first object for sure, thank you! – Shady Goat Dec 07 '20 at 17:48
0

Write a function that makes a copy of the first object and adds the keys in:

function addProperties(firstObj, secondObj) {
  const newObj = Object.assign({}, firstObj);
  for (let key of Object.keys(secondObj)) {
    if (newObj.hasOwnProperty(key)) {
      newObj[key] += secondObj[key];
    } else {
      newObj[key] = secondObj[key];
    }
  }
  return newObj;
}

const first = {
    age: 0,
    lvl: 123,
    xp: 321
};
const second = {
    age: 12,
    lvl: 21
};

const result = addProperties(first, second);
console.log(result);
TKoL
  • 13,158
  • 3
  • 39
  • 73