For example :
Here We do not need recursion and do not need to merge functions, just methods on flat objects.
ECMAScript (ES6) Standard Method
Method for ES5 and Earlier
Note: 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.
Here using JQuery extend method.
It can merge two objects together and all their properties.
From JQuery’s :
- Now settings contains the merged settings and options objects
- Here we can merge two objects into one new object:
- 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, we may use Object.keys for the same functionality instead:
- We are changed names from def and obj to target and source because they make more sense to me.
- We have also included as simple isArray function.
Note :We don’t like using the constructor property as it’s public and we might get an own property rather than the inherited one, so we changed the test for object.
- If we test of an object, then for an array, what falls through should be a primitve.
- There are a lot of assumptions here, we did implement a bit more checking to make sure getting what we expected.
- Merge two objects, modifying the first.
Using jQuery :
- The above code will mutate the object named settings.
- If we want to create a new object without modifying either argument, use this:
- The Harmony ECMAScript 2015 (ES6) specifies Object.assign which will do this.
- Object.assign(obj1, obj2);
Current browser support is getting better, but if we are developing for browsers that don’t have support, we can use a polyfill.
- Produces object o3 like
- Note that underscore.js’s extend-method does this in a one-liner:
- Similar to jQuery extend(), you have the same function in AngularJS: