ES5 Object.assign equivalent

为君一笑 提交于 2019-12-20 08:49:02

问题


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?


回答1:


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



回答2:


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



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!