How to duplicate object properties in another object?

Per ES6 - Spread syntax:

You can simply use:

const thirdObject = {
   ...firstObject,
   ...secondObject   
}

This avoids problems of passing these objects by reference.

Additionally it takes care of objects that have deep nesting.


Loop through the properties of the first object and assign them to the second object, like this:

var firstObject = {
    key1 : 'value1',
    key2 : 'value2'
};

var secondObject = {
    key3 : 'value3',
    key4 : 'value4'
};

for (var prop in firstObject) {
    if (firstObject.hasOwnProperty(prop)) {
        secondObject[prop] = firstObject[prop];
    }
}

The for-in loop isn't enough; you need hasOwnProperty. See http://bonsaiden.github.com/JavaScript-Garden/#object.forinloop for a detailed explanation of why.


Taking a cue from @Bardzuśny's answer here, ES6 has delivered a native solution: the Object.assign() function!

Usage is simple:

Object.assign(secondObject, firstObject);

That's it!

Support right now is obviously poor; only Firefox (34+) supports it out-of-the-box, while Chrome (45+) and Opera (32+) require the 'experimental flag' to be set.

Support is improving, with the lastest versions of Chrome, Firefox, Opera, Safari and Edge supporting it (IE notably has no support.) Transpilers are available as well, like Babel and Traceur. See here for more details.


for(var k in firstObject) secondObject[k]=firstObject[k];

Tags:

Javascript