How can I merge properties of two JavaScript objec

2018-12-30 22:14发布

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:

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

obj1.merge(obj2);

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

Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.

30条回答
琉璃瓶的回忆
2楼-- · 2018-12-30 22:51

In MooTools, there's Object.merge():

Object.merge(obj1, obj2);
查看更多
呛了眼睛熬了心
3楼-- · 2018-12-30 22:51

Merging objects is simple.

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog', car: 'BMW' }
var obj3 = {a: "A"}


var mergedObj = Object.assign(obj1,obj2,obj3)

console.log(mergedObj);

The objects are merged from right to left, this means that objects which have identical properties as the objects to their right will be overriden.

In this example obj2.car overrides obj1.car

查看更多
荒废的爱情
4楼-- · 2018-12-30 22:57

The Harmony ECMAScript 2015 (ES6) specifies Object.assign which will do this.

Object.assign(obj1, obj2);

Current browser support is getting better, but if you're developing for browsers that don't have support, you can use a polyfill.

查看更多
余欢
5楼-- · 2018-12-30 22:57

There's a library called deepmerge on GitHub: That seems to be getting some traction. It's a standalone, available through both the npm and bower package managers.

I would be inclined to use or improve on this instead of copy-pasting code from answers.

查看更多
看淡一切
6楼-- · 2018-12-30 22:58

Note that underscore.js's extend-method does this in a one-liner:

_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}
查看更多
骚的不知所云
7楼-- · 2018-12-30 22:58

In Ext JS 4 it can be done as follows:

var mergedObject = Ext.Object.merge(object1, object2)

// Or shorter:
var mergedObject2 = Ext.merge(object1, object2)

See merge( object ) : Object.

查看更多
登录 后发表回答