javascript tutorial - [Solved-5 Solutions] Merge properties of two javascript objects dynamically?
- javascript - java script - javascript array
Problem:
We need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:
Does anyone have a script for this or know of a built in way to do this? WE do not need recursion, and WE do not need to merge functions, just methods on flat objects.
Solution 1:
ECMAScript 2015 (ES6) Standard Method
Method for ES5 and Earlier
Note that this will simply add all attributes of obj2 to obj1 which might not be what we want if we still want to use the unmodified obj1.
If you're using a framework that craps all over our prototypes then we have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.
Example function:
Solution 2:
jQuery also has a utility for this: .
Taken from the jQuery documentation:
jQuery also has a utility for this: jQuery.extend.
Taken from the jQuery documentation:
The above code will mutate the object named settings.
If we want to create a new object without modifying either argument, use this:
Solution 3:
The Harmony ECMAScript 2015 (ES6) specifies Object.assign which will do this.
Object.assign(obj1, obj2);
Current browser support is getting better es6, but if you're developing for browsers that don't have support, we can use a polyfill.