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.
ECMAScript 2018 Standard Method
You would use object spread:
mergedis now the union ofobj1andobj2. Properties inobj2will overwrite those inobj1.Here is also the MDN documentation for this syntax. If you’re using babel you’ll need the @babel/plugin-proposal-object-rest-spread plugin for it to work (This plugin is included in
@babel/preset-env, in ES2018).ECMAScript 2015 (ES6) Standard Method
(see MDN JavaScript Reference)
Method for ES5 and Earlier
Note that this will simply add all attributes of
obj2toobj1which might not be what you want if you still want to use the unmodifiedobj1.If you’re using a framework that craps all over your prototypes then you have to get fancier with checks like
hasOwnProperty, but that code will work for 99% of cases.Example function:
additionally :- check this program for see differnce between Object.assign & spread syntax object literals