我需要能够在运行时合并两个(非常简单)JavaScript对象。例如,我想:

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

是否有一种内置的方法来实现这一点?我不需要递归,也不需要合并函数,只需要平面对象上的方法。


当前回答

使用Undercore.js,要合并对象数组,请执行以下操作:

var arrayOfObjects = [ {a:1}, {b:2, c:3}, {d:4} ];
_(arrayOfObjects).reduce(function(memo, o) { return _(memo).extend(o); });

结果是:

Object {a: 1, b: 2, c: 3, d: 4}

其他回答

在一行代码中合并N个对象的财产

Object.assign方法是ECMAScript 2015(ES6)标准的一部分,它完全符合您的需要。(不支持IE)

var clone = Object.assign({}, obj);

assign()方法用于将所有可枚举自身财产的值从一个或多个源对象复制到目标对象。

阅读更多。。。

支持旧浏览器的polyfill:

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(nextSource);
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}
Object.assign(TargetObject, Obj1, Obj2, ...);

使用jQuery库尝试这种方式

let obj1 = { food: 'pizza', car: 'ford' }
let obj2 = { animal: 'dog' }

console.log(jQuery.extend(obj1, obj2))

使用object.assign和spread运算符合并两个对象。

错误的方式(修改原始对象,因为目标是o1)

var o1 = { X: 10 };
var o2 = { Y: 20 };
var o3 = { Z: 30 };
var merge = Object.assign(o1, o2, o3);
console.log(merge)  // {X:10, Y:20, Z:30}
console.log(o1)     // {X:10, Y:20, Z:30}

正确的方式

Object.assign({},o1,o2,o3)==>以新对象为目标{…o1,…o2,…o3}==>扩展对象

变量o1={X:10};var o2={Y:20};var o3={Z:30};console.log('不修改原始对象,因为目标{}');var merge=对象赋值({},o1,o2,o3);console.log(合并);//{X:10,Y:20,Z:30}控制台日志(o1)console.log('不修改原始对象')var spreadMerge={…o1,…o2,…o3};console.log(spreadMerge);控制台日志(o1);

您可以使用对象排列语法来实现这一点。这是ES2018及以后的一部分。

constobj1={food:“pizza”,car:“ford”};const obj2={animal:“狗”};常量obj3={…obj1,…obj2};console.log(obj3);