ES5 Object.assign equivalent

我怕爱的太早我们不能终老 提交于 2019-12-02 17:09:27

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