Various ways javaScript combines objects:
1. Method 1: Object.assign(obj1, obj2, …)
Parameter 1: obj1 is the target object
Parameter 2: obj2 is the source objectNote: between objects, the attribute with the same name will be overwritten by the attribute value of the object behind
const obj1 = {
a: 1,
b: 2,
}
const obj2 = {
b: 3,
c: 4,
}
const result = Object.assign(obj1, obj2)
console.log(result) // {a: 1, b: 3, c: 4}
2. Method 2: es6 new syntax, expansion operator... [Three points]
{...obj1, ...obj2}
Note: between objects, the attributes with the same name will be overwritten by the attribute values of the following objects
const obj1 = {
a: 1,
b: 2,
}
const obj2 = {
b: 3,
c: 4,
}
const result = {
...obj1, ...obj2} // 返回一个新的对象。
console.log(result) // {a: 1, b: 3, c: 4}
// 顺带一提, 数组之间的合并,也可以使用 扩展运算符 .
// 如: [...arr1, ...arr2]
Knowledge expansion:
The spread operator... [Three points] can also be used for merging between arrays.
The difference is:
the arrays will only be merged, even if they are the same value, they will not be overwritten. (This is where it differs from objects.)
let arr1 = [1,2,4]
let arr2 = [4,5,6]
let arr3 = [...arr1, ...arr2]
console.log(arr3) // [1, 2, 4, 4, 5, 6]