ECMAScript 2018 Standard Method
(ECMAScript 2018标准方法)
You would use object spread :
(您将使用对象传播 :)
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};
Here is also the MDN documentation for this syntax, and if you're using babel- you'll need this plugin for it to work.
(这也是该语法的MDN文档 ,如果您使用的是babel,则需要此插件才能正常工作。)
ECMAScript 2015 (ES6) Standard Method
(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);
(see MDN JavaScript Reference )
((请参阅MDN JavaScript参考 ))
Method for ES5 and Earlier
(ES5和更早版本的方法)
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
Note that this will simply add all attributes of obj2
to obj1
which might not be what you want if you still want to use the unmodified obj1
.
(请注意,这只会将obj2
所有属性添加到obj1
,如果您仍想使用未修改的obj1
,则可能不是您想要的。)
If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty
, but that code will work for 99% of cases.
(如果您使用的框架覆盖了您的所有原型,那么您必须对hasOwnProperty
这样的检查变得hasOwnProperty
,但是该代码将在99%的情况下都能正常工作。)
Example function:
(示例功能:)
/**
* 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;
}