I wanted to do something which is very straight-forward using Object.assign
.
var firstObj = {name : "Saba H.", rollNo : 1}; var secondObj = {college : "WCE"}; var wholeObj = Object.assign(firstObj, secondObj); console.log(wholeObj); // {name : "Saba H.", rollNo : 1, college : "WCE"}
As Object.assign
is part of ECMAScript6 harmony proposal and not supported across many browsers, is it possible to do with ES5? If not then is there any micro library?
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Input : var obj1 = { a: 10 }; var obj2 = { b: 20 }; var obj3 = { c: 30 }; var new_obj = Object. assign(obj1, obj2, obj3); console. log(new_obj); Output : Object { a: 10, b: 20, c: 30 } Explanation: Here in this example the properties of three source objects "obj1, obj2, obj3" are copied to the target object "new_obj".
assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
The difference is that Object. assign changes the object in-place, while the spread operator ( ... ) creates a brand new object, and this will break object reference equality.
In underscore.js you can use like,
_.extend(firstObj, secondObj);
In jQuery, you can use,
$.extend({},firstObj,secondObj);
In pure javascipt, you can merge n
number of objects by using this function:
function mergeObjects() { var resObj = {}; for(var i=0; i < arguments.length; i += 1) { var obj = arguments[i], keys = Object.keys(obj); for(var j=0; j < keys.length; j += 1) { resObj[keys[j]] = obj[keys[j]]; } } return resObj; }
I found a working polyfill for Object.assign on MDN (awesome, thanks!):
if (typeof Object.assign != 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 'use strict'; if (target == null) { // TypeError if undefined or null throw new TypeError('Cannot convert undefined or null to object'); } var to = Object(target); for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index]; if (nextSource != null) { // Skip over if undefined or null for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; } } } } return to; }, writable: true, configurable: true }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With