ECMAScript 2018 标准方法
您将使用对象跨页:
let merged = {...obj1, ...obj2};
merged
现在是 和 的并集。中的属性将覆盖 中的属性。obj1
obj2
obj2
obj1
/** 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};
下面也是此语法的 MDN 文档。如果你使用的是 babel,你需要 babel-plugin-transform-object-rest-spread 插件才能工作。
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 Reference)
适用于 ES5 及更早版本的方法
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
请注意,如果您仍然想使用未修改的 .,这将简单地添加可能不是您想要的所有属性。obj2
obj1
obj1
如果你使用的框架在你的原型上到处都是,那么你必须通过像 这样的检查变得更花哨,但该代码将适用于99%的情况。hasOwnProperty
示例函数:
/**
* 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;
}