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;
}
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
});
}
The pure javascript way:
function mergeObjects(){
var res = {};
for(var i = 0;i<arguments.length;i++){
for(x in arguments[i]){
res[x] = arguments[i][x];
};
};
return res;
};
Example:
var my_merged_object = mergeObjects(obj1,obj2,...);
来源:https://stackoverflow.com/questions/30498318/es5-object-assign-equivalent