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

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

obj1.merge(obj2);

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

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


当前回答

对于使用Node.js的用户,有一个NPM模块:Node.extend

安装:

npm install node.extend

用法:

var extend = require('node.extend');
var destObject = extend(true, {}, sourceObject);
// Where sourceObject is the object whose properties will be copied into another.

其他回答

请注意,underline.js的extend方法在一行中实现了这一点:

_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}

有不同的方法可以实现这一点:

Object.assign(targetObj, sourceObj);

targetObj = {...targetObj, ...sourceObj};

对于使用Node.js的用户,有一个NPM模块:Node.extend

安装:

npm install node.extend

用法:

var extend = require('node.extend');
var destObject = extend(true, {}, sourceObject);
// Where sourceObject is the object whose properties will be copied into another.

有三种方法可以做到这一点:-

方法1:-

// using spread ...
    let obj1 = {
        ...obj2
    };

方法2:-

// using  Object.assign() method
let obj1 = Object.assign({}, obj2);

方法3:-

// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));

使用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}