阅读量:1
ES6合并对象的方法有以下几种:
使用对象展开运算符(…):
const obj1 = {a: 1, b: 2}; const obj2 = {c: 3, d: 4}; const merged = {...obj1, ...obj2}; console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
使用Object.assign()方法:
const obj1 = {a: 1, b: 2}; const obj2 = {c: 3, d: 4}; const merged = Object.assign({}, obj1, obj2); console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
使用Object.getOwnPropertyDescriptors()方法和Object.defineProperties()方法:
const obj1 = {a: 1, b: 2}; const obj2 = {c: 3, d: 4}; const descriptors = Object.getOwnPropertyDescriptors(obj2); const merged = Object.defineProperties(obj1, descriptors); console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
这些方法都可以用来合并多个对象的属性,并创建一个新的对象。