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?
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;
}