3294

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

Is there a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.

2
  • Its worth noting this answer on a similar question, which shows how to merge "one level down". That is, it merges values of duplicate keys (instead of overwriting first value with second value), but does not recurse further than that. IMHO, its good clean code for that task. Oct 3, 2019 at 21:42
  • BTW, the top few answers do a "shallow" merge: if the same key exists in both obj1 and obj2, the value in obj2 is kept, the value in obj1 is dropped. E.g. if question's example had var obj2 = { animal: 'dog', food: 'bone' };, the merge would be { food: 'bone', car: 'ford', animal: 'dog' }. If you are working with "nested data", and want a "deep merge", then look for answers that mention "deep merge" or "recursion". If you have values that are arrays, then use "arrayMerge" option of github "TehShrike/deepmerge", as mentioned here. Oct 4, 2019 at 12:30

69 Answers 69

6

With Underscore.js, to merge an array of objects do:

var arrayOfObjects = [ {a:1}, {b:2, c:3}, {d:4} ];
_(arrayOfObjects).reduce(function(memo, o) { return _(memo).extend(o); });

It results in:

Object {a: 1, b: 2, c: 3, d: 4}
5

You should use lodash's defaultsDeep

_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
// → { 'user': { 'name': 'barney', 'age': 36 } }
5

It's worth mentioning that the version from the 140byt.es collection is solving the task within minimum space and is worth a try for this purpose:

Code:

function m(a,b,c){for(c in b)b.hasOwnProperty(c)&&((typeof a[c])[0]=='o'?m(a[c],b[c]):a[c]=b[c])}

Usage for your purpose:

m(obj1,obj2);

Here's the original Gist.

4

ES2018/TypeScript: Many answers are OK but I've come up with a more elegant solution to this problem when you need to merge two objects without overwriting overlapping object keys.

My function also accepts unlimited number of objects to merge as function arguments:

(I'm using TypeScript notation here, feel free to delete the :object[] type in the function argument if you're using plain JavaScript).

const merge = (...objects: object[]) => {
  return objects.reduce((prev, next) => {
    Object.keys(prev).forEach(key => {
      next[key] = { ...next[key], ...prev[key] }
    })
    return next
  })
}
1
4

Use Spread operator which follows the ES6 version

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
let result = {...obj1,...obj2};
console.log(result)

output { food: 'pizza', car: 'ford', animal: 'dog' }
4

You can use Object.assign method. For example:

var result = Object.assign(obj1, obj2);

Also, note that it creates a shallow copy of the object.

2

My way:

function mergeObjects(defaults, settings) {
    Object.keys(defaults).forEach(function(key_default) {
        if (typeof settings[key_default] == "undefined") {
            settings[key_default] = defaults[key_default];
        } else if (isObject(defaults[key_default]) && isObject(settings[key_default])) {
            mergeObjects(defaults[key_default], settings[key_default]);
        }
    });

    function isObject(object) {
        return Object.prototype.toString.call(object) === '[object Object]';
    }

    return settings;
}

:)

2

Use:

//Takes any number of objects and returns one merged object
var objectMerge = function(){
    var out = {};
    if(!arguments.length)
        return out;
    for(var i=0; i<arguments.length; i++) {
        for(var key in arguments[i]){
            out[key] = arguments[i][key];
        }
    }
    return out;
}

It was tested with:

console.log(objectMerge({a:1, b:2}, {a:2, c:4}));

It results in:

{ a: 2, b: 2, c: 4 }
2

gossi's extension of David Coallier's method:

Check these two lines:

from = arguments[i];
Object.getOwnPropertyNames(from).forEach(function (name) {

One need to check "from" against null object... If for example merging an object that comes from an Ajax response, previously created on a server, an object property can have a value of "null", and in that case the above code generates an error saying:

"from" is not a valid object

So for example, wrapping the "...Object.getOwnPropertyNames(from).forEach..." function with an "if (from != null) { ... }" will prevent that error occurring.

0
2

I use the following which is in pure JavaScript. It starts from the right-most argument and combines them all the way up to the first argument. There is no return value, only the first argument is modified and the left-most parameter (except the first one) has the highest weight on properties.

var merge = function() {
  var il = arguments.length;

  for (var i = il - 1; i > 0; --i) {
    for (var key in arguments[i]) {
      if (arguments[i].hasOwnProperty(key)) {
        arguments[0][key] = arguments[i][key];
      }
    }
  }
};
2

function extend(o, o1, o2){
    if( !(o instanceof Object) ) o = {};

    copy(o, o1);
    if( o2 )
        copy(o, o2)

    function isObject(obj) {
        var type = Object.prototype.toString.call(obj);
        return obj === Object(obj) && type != '[object Array]' && type != '[object Function]';
    };

    function copy(a,b){
        // copy o2 to o
        for( var key in b )
            if( b.hasOwnProperty(key) ){
                if( isObject(b[key]) ){
                    if( !isObject(a[key]) )
                        a[key] = Object.assign({}, b[key]); 
                    else copy(a[key], b[key])
                }
                else
                    a[key] = b[key];
            }
    }

    return o;
};


var o1 = {a:{foo:1}, b:1},
    o2 = {a:{bar:2}, b:[1], c:()=>{}},
    newMerged = extend({}, o1, o2);
    
console.log( newMerged )
console.log( o1 )
console.log( o2 )

6
  • 4
    This falls over if o2 contains any properties that don't already exist in o1, which is exactly why Markus has the try/catch you've removed. Your example only works because all of o2's properties already exist in o1. So, this isn't a merge, and it isn't better!
    – pancake
    Apr 24, 2012 at 5:02
  • no it doesn't fail, I've just tried what you've said with success.
    – vsync
    Sep 3, 2013 at 12:16
  • One should note that the function is destructive and obj1 as well as any objects nested inside it will be modified, which may or may not be what you wanted. I renamed the function and arguments to applyProperties(target, source) myself for clarity. Apr 4, 2016 at 15:51
  • @mindplay.dk - what do you mean destructive? the point is to merge o2 into o1, not to create a new (third) object of o1 merged with o2. I answered the exact question
    – vsync
    Apr 4, 2016 at 18:06
  • @vsync destructive in the sense that e.g. Array.sort() is destructive and Array.slice() isn't - it's not a criticism, just pointing out a fact :-) Apr 9, 2016 at 14:48
2

With the following helper, you can merge two objects into one new object:

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

// example
var a = { foo: true }, b = { bar: false };
var c = extend(a, b);

console.log(c);
// { foo: true, bar: false }

This is typically useful when merging an options dict with the default settings in a function or a plugin.

If support for IE 8 is not required, you may use Object.keys for the same functionality instead:

function extend(obj, src) {
    Object.keys(src).forEach(function(key) { obj[key] = src[key]; });
    return obj;
}

This involves slightly less code and is a bit faster.

2

The Merge Of JSON Compatible JavaScript Objects

I encourage the use and utilization of nondestructive methods that don't modify the original source, 'Object.assign' is a destructive method and it also happens to be not so production friendly because it stops working on earlier browsers and you have no way of patching it cleanly, with an alternative.

Merging JS Objects will always be out of reach, or incomplete, whatever the solution. But merging JSON compliant compatible objects is just one step away from being able to write a simple and portable piece of code of a nondestructive method of merging series of JS Objects into a returned master containing all the unique property-names and their corresponding values synthesized in a single master object for the intended purpose.

Having in mind that MSIE8 is the first browser to have added a native support for the JSON object is a great relief, and reusing the already existing technology, is always a welcomed opportunity.

Restricting your code to JSON complant standard objects, is more of an advantage, than a restriction - since these objects can also be transmitted over the Internet. And of course for those who would like a deeper backward compatibility there's always a json plug., whose methods can easily be assigned to a JSON variable in the outer code without having to modify or rewrite the method in use.

function Merge( ){
    var a = [].slice.call( arguments ), i = 0;
        while( a[i] )a[i] = JSON.stringify( a[i++] ).slice( 1,-1 );
        return JSON.parse( "{"+ a.join() +"}" );
    }

(Of course one can always give it a more meaningful name, which I haven't decided yet; should probably name it JSONmerge)

The use case:

var master = Merge( obj1, obj2, obj3, ...objn );

Now, contrary to the Object.assign this leaves all objects untouched and in their original state (in case you've done something wrong and need to reorder the merging objects or be able to use them separately for some other operation before merging them again).

Tthe number of the Merge arguments is also limited only by the arguments length limit [which is huge]. The natively supported JSON parse / stringify is already machine optimized, meaning: it should be faster than any scripted form of JS loop. The iteration over given arguments, is being done using the while - proven to be the fastest loop in JS.

It doesn't harm to briefly mention the fact we already know that duplicate properties of the unique object labels (keys) will be overwritten by the later object containing the same key label, which means you are in control of which property is taking over the previous by simply ordering or reordering the arguments list. And the benefit of getting a clean and updated master object with no dupes as a final output.

;
var obj1 = {a:1}, obj2 = {b:2}, obj3 = {c:3}
;
function Merge( ){
    var a = [].slice.call( arguments ), i = 0;
        while( a[i] )a[i] = JSON.stringify( a[i++] ).slice( 1,-1 );
        return JSON.parse( "{"+ a.join() +"}" );
    }
;
var master = Merge( obj1, obj2, obj3 )
;
console.log( JSON.stringify( master ) )
;

2

merge two object using Object.assign and spread operator.

Wrong way(Modify original object because targeting o1)

var o1 = { X: 10 };
var o2 = { Y: 20 };
var o3 = { Z: 30 };
var merge = Object.assign(o1, o2, o3);
console.log(merge)  // {X:10, Y:20, Z:30}
console.log(o1)     // {X:10, Y:20, Z:30}

Right ways

  • Object.assign({}, o1, o2, o3) ==> targeting new object

  • {...o1, ...o2, ...o3} ==> spreading objects

var o1 = { X: 10 };
var o2 = { Y: 20 };
var o3 = { Z: 30 };

console.log('Does not modify original objects because target {}');
var merge = Object.assign({}, o1, o2, o3);
console.log(merge); // { X: 10, Y: 20, Z: 30 }
console.log(o1)

console.log('Does not modify original objects')
var spreadMerge = {...o1, ...o2, ...o3};
console.log(spreadMerge);
console.log(o1);

2

shallow

var obj = { name : "Jacob" , address : ["America"] }
var obj2 = { name : "Shaun" , address : ["Honk Kong"] }

var merged = Object.assign({} , obj,obj2 ); //shallow merge 
obj2.address[0] = "new city"

result.address[0] is changed to "new city" , i.e merged object is also changed. This is the problem with shallow merge.

deep

var obj = { name : "Jacob" , address : ["America"] }
var obj2 = { name : "Shaun" , address : ["Honk Kong"] }

var result = Object.assign({} , JSON.parse(JSON.stringify(obj)),JSON.parse(JSON.stringify(obj2)) )

obj2.address[0] = "new city"

result.address[0] is not changed

1
  • var merged = Object.assign({} , obj,obj2 ) does not merge anything? Nov 16, 2020 at 20:32
2

There are different ways to achieve this:

Object.assign(targetObj, sourceObj);

targetObj = {...targetObj, ...sourceObj};
2
Object.assign(TargetObject, Obj1, Obj2, ...);
2

Use this

var t=merge({test:123},{mysecondTest:{blub:{test2:'string'},args:{'test':2}}})
console.log(t);

function merge(...args) {
  return Object.assign({}, ...args);
}

1

I've used Object.create() to keep the default settings (utilising __proto__ or Object.getPrototypeOf() ).

function myPlugin( settings ){
    var defaults = {
        "keyName": [ "string 1", "string 2" ]
    }
    var options = Object.create( defaults );
    for (var key in settings) { options[key] = settings[key]; }
}
myPlugin( { "keyName": ["string 3", "string 4" ] } );

This way I can always 'concat()' or 'push()' later.

var newArray = options['keyName'].concat( options.__proto__['keyName'] );

Note: You'll need to do a hasOwnProperty check before concatenation to avoid duplication.

1

You can merge objects through following my method

var obj1 = { food: 'pizza', car: 'ford' };
var obj2 = { animal: 'dog' };

var result = mergeObjects([obj1, obj2]);

console.log(result);
document.write("result: <pre>" + JSON.stringify(result, 0, 3) + "</pre>");

function mergeObjects(objectArray) {
    if (objectArray.length) {
        var b = "", i = -1;
        while (objectArray[++i]) {
            var str = JSON.stringify(objectArray[i]);
            b += str.slice(1, str.length - 1);
            if (objectArray[i + 1]) b += ",";
        }
        return JSON.parse("{" + b + "}");
    }
    return {};
}

1

I'm kind of getting started with JavaScript, so correct me if I'm wrong.

But wouldn't it be better if you could merge any number of objects? Here's how I do it using the native Arguments object.

The key to is that you can actually pass any number of arguments to a JavaScript function without defining them in the function declaration. You just can't access them without using the Arguments object.

function mergeObjects() (
    var tmpObj = {};

    for(var o in arguments) {
        for(var m in arguments[o]) {
            tmpObj[m] = arguments[o][m];
        }
    }
    return tmpObj;
}
1

In YUI Y.merge should get the job done:

Y.merge(obj1, obj2, obj3....) 
1

For those using Node.js, there's an NPM module: node.extend

Install:

npm install node.extend

Usage:

var extend = require('node.extend');
var destObject = extend(true, {}, sourceObject);
// Where sourceObject is the object whose properties will be copied into another.
1
  • 1
    This is not a builtin library, it's a NPM module. Apr 29, 2014 at 20:34
1

ES5 compatible native one-liner:

var merged = [obj1, obj2].reduce(function(a, o) { for(k in o) a[k] = o[k]; return a; }, {})
1

Three ways you can do that:-

Approach 1:-

// using spread ...
    let obj1 = {
        ...obj2
    };

Approach2:-

// using  Object.assign() method
let obj1 = Object.assign({}, obj2);

Approach3:-

// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));
1
  • The question was how to merge two objects, this answer is just copying an object.
    – user9645
    Aug 24, 2023 at 13:21
0

This merges obj into a "default" def. obj has precedence for anything that exists in both, since obj is copied into def. Note also that this is recursive.

function mergeObjs(def, obj) {
    if (typeof obj == 'undefined') {
        return def;
    } else if (typeof def == 'undefined') {
        return obj;
    }
    for (var i in obj) {
        if (obj[i] != null && obj[i].constructor == Object) {
            def[i] = mergeObjs(def[i], obj[i]);
        } else {
            def[i] = obj[i];
        }
    }
    return def;
}

a = {x : {y : [123]}}
b = {x : {z : 123}}
console.log(mergeObjs(a, b));
// {x: {y : [123], z : 123}}
0
A={a:1,b:function(){alert(9)}}
B={a:2,c:3}
A.merge = function(){for(var i in B){A[i]=B[i]}}
A.merge()

Result is: {a:2,c:3,b:function()}

1
  • btw, dojo has a function called mixin so, dojo.mixin(A,B) will do the trick Dec 19, 2012 at 17:41
0

This solution creates a new object and is able to handle multiple objects.

Furthermore, it is recursive and you can chose weather you want to overwrite Values and Objects.

    function extendObjects() {

        var newObject        = {};
        var overwriteValues  = false;
        var overwriteObjects = false;

        for ( var indexArgument = 0; indexArgument < arguments.length; indexArgument++ ) {

            if ( typeof arguments[indexArgument] !== 'object' ) {

                if ( arguments[indexArgument] == 'overwriteValues_True' ) {

                    overwriteValues = true;            
                } else if ( arguments[indexArgument] == 'overwriteValues_False' ) {

                    overwriteValues = false;                             
                } else if ( arguments[indexArgument] == 'overwriteObjects_True' ) {

                    overwriteObjects = true;     
                } else if ( arguments[indexArgument] == 'overwriteObjects_False' ) {

                    overwriteObjects = false; 
                }

            } else {

                extendObject( arguments[indexArgument], newObject, overwriteValues, overwriteObjects );
            }

        }

        function extendObject( object, extendedObject, overwriteValues, overwriteObjects ) {

            for ( var indexObject in object ) {

                if ( typeof object[indexObject] === 'object' ) {

                    if ( typeof extendedObject[indexObject] === "undefined" || overwriteObjects ) {
                        extendedObject[indexObject] = object[indexObject];
                    }

                    extendObject( object[indexObject], extendedObject[indexObject], overwriteValues, overwriteObjects );

                } else {

                    if ( typeof extendedObject[indexObject] === "undefined" || overwriteValues ) {
                        extendedObject[indexObject] = object[indexObject];
                    }

                }

            }     

            return extendedObject;

        }

        return newObject;
    }

    var object1           = { a : 1, b : 2, testArr : [888, { innArr : 1 }, 777 ], data : { e : 12, c : { lol : 1 }, rofl : { O : 3 } } };
    var object2           = { a : 6, b : 9, data : { a : 17, b : 18, e : 13, rofl : { O : 99, copter : { mao : 1 } } }, hexa : { tetra : 66 } };
    var object3           = { f : 13, g : 666, a : 333, data : { c : { xD : 45 } }, testArr : [888, { innArr : 3 }, 555 ]  };

    var newExtendedObject = extendObjects( 'overwriteValues_False', 'overwriteObjects_False', object1, object2, object3 );

Contents of newExtendedObject:

{"a":1,"b":2,"testArr":[888,{"innArr":1},777],"data":{"e":12,"c":{"lol":1,"xD":45},"rofl":{"O":3,"copter":{"mao":1}},"a":17,"b":18},"hexa":{"tetra":66},"f":13,"g":666}

Fiddle: http://jsfiddle.net/o0gb2umb/

0

A possible way to achieve this is the following.

if (!Object.prototype.merge){
    Object.prototype.merge = function(obj){
        var self = this;
        Object.keys(obj).forEach(function(key){
            self[key] = obj[key]
        });
    }
};

I don't know if it's better then the other answers. In this method you add the merge function to Objects prototype. This way you can call obj1.merge(obj2);

Note : you should validate your argument to see if its an object and 'throw' a proper Error. If not Object.keys will 'throw' an 'Error'

0

The correct implementation in Prototype should look like this:

var obj1 = {food: 'pizza', car: 'ford'}
var obj2 = {animal: 'dog'}

obj1 = Object.extend(obj1, obj2);

Not the answer you're looking for? Browse other questions tagged or ask your own question.