ES5 Object.assign等价物

时间:2015-05-28 05:58:20

标签: javascript object ecmascript-5 ecmascript-harmony

我希望使用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"}

由于Object.assign是ECMAScript6和谐提案的一部分,并且在许多浏览器中都不支持,因此可以使用ES5吗?如果没有,那么有没有微型图书馆?

5 个答案:

答案 0 :(得分:33)

在underscore.js中你可以使用like,

_.extend(firstObj, secondObj);

在jQuery中,你可以使用,

$.extend({},firstObj,secondObj);

在纯javascipt中,您可以使用此函数合并n个对象:

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

答案 1 :(得分:3)

我在MDN找到了一个用于Object.assign的聚合填充物(太棒了,谢谢!):

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

答案 2 :(得分:1)

纯JavaScript方式:

function mergeObjects(){
    var res = {};
    for(var i = 0;i<arguments.length;i++){
        for(x in arguments[i]){
            res[x] = arguments[i][x];
        };
    };
    return res;
};

示例:

var my_merged_object = mergeObjects(obj1,obj2,...);

答案 3 :(得分:1)

var extend = function ( defaults, options ) {
    var extended = {};
    var prop;
    for (prop in defaults) {
        if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
            extended[prop] = defaults[prop];
        }
    }
    for (prop in options) {
        if (Object.prototype.hasOwnProperty.call(options, prop)) {
            extended[prop] = options[prop];
        }
    }
    return extended;
};
var settings = extend(defaults, options);

答案 4 :(得分:-1)

使用扩展运算符

var firstObj = {name : "Saba H.", rollNo : 1},
secondObj = {college : "WCE"},
wholeObj = {...firstObj, ...secondObj};

console.log(wholeObj); // {name : "Saba H.", rollNo : 1, college : "WCE"}