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
Does anyone have a script for this or know of 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.
In MooTools, there's Object.merge():
Merging objects is simple.
The objects are merged from right to left, this means that objects which have identical properties as the objects to their right will be overriden.
In this example
obj2.car
overridesobj1.car
The Harmony ECMAScript 2015 (ES6) specifies
Object.assign
which will do this.Current browser support is getting better, but if you're developing for browsers that don't have support, you can use a polyfill.
There's a library called
deepmerge
on GitHub: That seems to be getting some traction. It's a standalone, available through both the npm and bower package managers.I would be inclined to use or improve on this instead of copy-pasting code from answers.
Note that
underscore.js
'sextend
-method does this in a one-liner:In Ext JS 4 it can be done as follows:
See merge( object ) : Object.