0

Suppose I have this object:

let obj1 = {
key1: 'value1',
key2: 'value2'
}

And I have a different object like this:

let obj2 = {
key3: 'value3',
key4: 'value4'
}

Is there a way of adding obj2 properties to obj1 and have this?

{
    key1: 'value1',
    key2: 'value2',
    key3: 'value3',
    key4: 'value4'
}

I currently have this working but would want to know if there is an easier way:

for (prop in obj2) {
        if (obj2.hasOwnProperty(prop)) {
          obj1[prop] = obj2[prop];
        }
      }
1
  • actually there are several ways on of them is obj1 = Object.assign(obj1, obj2) Commented Aug 29, 2018 at 17:18

3 Answers 3

9

The easiest way of achieving this is using Object's assign:

Object.assign(obj1, obj2);

where the first object (obj1) is the target and will get modified.

Sign up to request clarification or add additional context in comments.

Comments

1

According to Object Spread , you could do it this way :

let mergedObjects = {...obj1, ...obj2};

1 Comment

This is very easy to use as well
0

You can use Object.assign():

let obj1 = {
  key1: 'value1',
  key2: 'value2'
}

let obj2 = {
  key3: 'value3',
  key4: 'value4'
}


console.log(Object.assign(obj1, obj2))

Comments