How to merge Objects together in JavaScript

How to Merge Objects in JavaScript

Sharing is Caring

Merging objects together in JavaScript isn’t very difficult although there’s quite a few different ways that it can be done.

Note, I’m not covering deep cloning for the sake of simplicity although this can be easily done through most of these different methods.

In ECMAScript 2015 (ES6), this can be done using Object.assign


var person = {
 FirstName: "Brian"
 LastName: "Cline"
}

var contactInfo = {
 Email: "something@brcline.com",
 Mobile: "000-000-0000"
}

var mergedPerson = Object.assign({}, person, contactInfo)

If we do a console.dir on the mergedPerson object we would see this in the console:

{
Email: "something@brcline.com",
FirstName: "Brian",
LastName: "Cline", 
Mobile: "000-000-0000"
}

Prior to browsers supporting ES6 we had to write code that would merge the objects by looping through the keys or make use of jQuery.

var person = {
 FirstName: "Brian"
 LastName: "Cline"
}

var contactInfo = {
 Email: "something@brcline.com",
 Mobile: "000-000-0000"
}

function mergeObjects(obj, src) {
    for (var key in src) {
        if (src.hasOwnProperty(key)) {
          obj[key] = src[key];
        }
    }

    return obj;
}

var mergedInfo = mergeObjects(person, contactInfo);

If you wanted to use the jQuery approach you could use the jQuery.extend method which basically works the same as my “mergeObjects” method.

And, finally, using the spread operator which is in proposal stages but is available already in some browsers it’s possible to merge objects in even shorter syntax.

var person = {
 FirstName: "Brian"
 LastName: "Cline"
}

var contactInfo = {
 Email: "something@brcline.com",
 Mobile: "000-000-0000"
}

var mergedInfo = {...person, ...contactInfo}

Sharing is Caring
,