How to merge Objects together 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

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.