Skip to content
Advertisement

How can I merge properties of two JavaScript objects dynamically?

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

JavaScript

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.

Advertisement

Answer

ECMAScript 2018 Standard Method

You would use object spread:

JavaScript

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

JavaScript

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

JavaScript

(see MDN JavaScript Reference)


Method for ES5 and Earlier

JavaScript

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

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:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement