定义let objOne = {a: 1}; let objTwo = {b: 2}; let objThree = {b: 2, c: 3};使用ES6的两种方法实现对象的去重合并
时间: 2024-05-01 14:18:16 浏览: 105
一种方法是使用对象展开运算符(...)和 Set 数据结构来实现去重合并:
```
const objOne = {a: 1};
const objTwo = {b: 2};
const objThree = {b: 2, c: 3};
const merged = {...objOne, ...objTwo, ...objThree};
const uniques = Array.from(new Set(Object.keys(merged))).reduce((result, key) => {
result[key] = merged[key];
return result;
}, {});
console.log(uniques); // {a: 1, b: 2, c: 3}
```
另一种方法是使用 Object.assign() 方法来实现去重合并:
```
const objOne = {a: 1};
const objTwo = {b: 2};
const objThree = {b: 2, c: 3};
const merged = Object.assign({}, objOne, objTwo, objThree);
const uniques = Array.from(new Set(Object.keys(merged))).reduce((result, key) => {
result[key] = merged[key];
return result;
}, {});
console.log(uniques); // {a: 1, b: 2, c: 3}
```
阅读全文