ES5 Object.assign equivalent
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
});
}