5 回答
TA贡献1886条经验 获得超2个赞
ECMAScript 2018标准方法
你会使用对象传播:
let merged = {...obj1, ...obj2};/** There's no limit to the number of objects you can merge.
* Later properties overwrite earlier properties with the same name. */const allRules = {...obj1, ...obj2, ...obj3};ECMAScript 2015(ES6)标准方法
/* For the case in question, you would do: */Object.assign(obj1, obj2);/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */const allRules = Object.assign({}, obj1, obj2, obj3, etc);(参见MDN JavaScript参考)
ES5和早期的方法
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }请注意,这会简单地添加的所有属性obj2,以obj1这可能不是你想要什么,如果你仍然想使用未修改obj1。
如果你使用的是一个遍布原型的框架,那么你必须得到更好的支票hasOwnProperty,但是这些代码适用于99%的情况。
功能示例:
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;}TA贡献1813条经验 获得超2个赞
在和谐的ECMAScript 2015年(ES6)规定Object.assign,将做到这一点。
Object.assign(obj1, obj2);
当前的浏览器支持正在变得越来越好,但如果您正在为没有支持的浏览器进行开发,则可以使用polyfill。
TA贡献1898条经验 获得超8个赞
我用google搜索代码来合并对象属性,最后来到这里。但是由于没有任何递归合并代码,我自己写了。(也许jQuery扩展是递归BTW?)无论如何,希望其他人也会觉得它很有用。
(现在代码不使用Object.prototype:)
码
/*
* Recursively merge properties of two objects
*/
function MergeRecursive(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor==Object ) {
obj1[p] = MergeRecursive(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
一个例子
o1 = { a : 1,
b : 2,
c : {
ca : 1,
cb : 2,
cc : {
cca : 100,
ccb : 200 } } };
o2 = { a : 10,
c : {
ca : 10,
cb : 20,
cc : {
cca : 101,
ccb : 202 } } };
o3 = MergeRecursive(o1, o2);
生成对象o3之类的
o3 = { a : 10,
b : 2,
c : {
ca : 10,
cb : 20,
cc : {
cca : 101,
ccb : 202 } } };
TA贡献1869条经验 获得超4个赞
请注意,underscore.js' extend-method在单行中执行此操作:
_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}添加回答
举报
