ES6 in 2015 introduced the spread operator, which is the perfect way to merge two simple objects into one:
2015年ES6引入了散布运算符 ,这是将两个简单对象合并为一个的完美方法:
const object1 = {
name : 'Flavio'
}
const object2 = {
age : 35
}
const object3 = {... object1 , ... object2 }
If both objects have a property with the same name, then the second object property overwrites the first.
如果两个对象都有一个具有相同名称的属性,则第二个对象属性将覆盖第一个对象。
The best solution in this case is to use Lodash and its merge()
method, which will perform a deeper merge, recursively merging object properties and arrays.
在这种情况下,最好的解决方案是使用Lodash及其merge()
方法 ,该方法将执行更深层的合并,以递归方式合并对象属性和数组。
See the documentation for it on the Lodash docs.
翻译自: https://flaviocopes.com/how-to-merge-objects-javascript/