es6 methods to merge objects are: 1. Use the "Object.assign()" method, syntax "Object.assign(obj1,obj2,obj3)"; 2. Use the expansion operator "... ", syntax "{...obj1,...obj2,...obj3}".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Method 1: Es6’s Object.assign()
Method
Object.assign() method is used to merge objects and merge the source objects All enumerable properties of (source) are copied to the target object (target).
Example:
let obj1 = {a: 1} let obj2 = {b: 2} let obj3 = {b: 3, c:4} let obj = Object.assign(obj1, obj2, obj3) console.log(obj, obj1, obj2, obj3)
Output:
{a: 1, b: 3, c: 4} {a: 1, b: 3, c: 4} {b: 2} {b: 3, c: 4}
Note
1. The first parameter of the Object.assign() method is the target object, and the following The parameters are all source objects.
2. Here, attribute b in obj2 is overwritten by attribute b in obj3.
Method 2: Use the spread operator
let obj1 = {a: 1} let obj2 = {b: 2} let obj3 = {b: 3, c:4} let objTwo = {...obj1,...obj2,...obj3} console.log(objTwo, obj1, obj2, obj3)
Execution result:
{a: 1, b: 3, c: 4} {a: 1, b: 3, c: 4} {b: 2} {b: 3, c: 4}
{...obj1,...obj2,... obj3} ...The form of the link is simpler and more crude!
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of What are the methods of merging objects in es6. For more information, please follow other related articles on the PHP Chinese website!