let arr = [ { a: "xinxin" }, { a: "pipi" }, { a: "zhazha" }, { a: "xinxin", c: 1 }, ]合并相同的key
时间: 2024-05-03 21:21:14 浏览: 98
One way to merge objects with the same key is to use reduce() method along with Object.keys() and Object.values() methods. Here's an example:
```
let arr = [
{ a: "xinxin" },
{ a: "pipi" },
{ a: "zhazha" },
{ a: "xinxin", c: 1 },
];
let result = arr.reduce((acc, curr) => {
let key = Object.keys(curr)[0];
if (acc[key]) {
acc[key] = Object.assign(acc[key], curr);
} else {
acc[key] = curr;
}
return acc;
}, {});
console.log(Object.values(result)); // [{a: "xinxin", c: 1}, {a: "pipi"}, {a: "zhazha"}]
```
In this example, the reduce() method is used to iterate over the array and accumulate the objects with the same key in the `acc` object. The `curr` object is checked for its key (using Object.keys() method) and if a matching key is found in `acc`, the objects are merged (using Object.assign() method) and stored in `acc`. Otherwise, `curr` is stored as is in `acc`. Finally, the `Object.values()` method is used to extract the values from the `result` object and return them as an array.
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)