let arr = [ { a: "xinxin", b: "zhazha" }, { a: "xinxin", b: "zhazha", c: 1 }];使用reduce合并相同key
时间: 2023-09-14 15:08:03 浏览: 48
const merged = arr.reduce((acc, current) => {
const key = current.a;
if (!acc[key]) {
acc[key] = { a: key };
}
acc[key] = { ...acc[key], ...current };
return acc;
}, {});
const result = Object.values(merged);
console.log(result); // [{ a: "xinxin", b: "zhazha", c: 1 }]
相关问题
let arr = [{ a: "xinxin", b: "zhazha" }, { a: "xinxin", b: "zhazha", c: 1 } ];根据相同的key合并数据
如果要根据相同的key合并数据,可以使用reduce方法,将每个对象的key作为reduce的参数,然后将相同key的对象合并在一起,最后返回一个新的对象数组。
例如,如果要根据key "a" 合并上面的数组,可以这样写:
```
let result = arr.reduce((acc, cur) => {
let index = acc.findIndex(item => item.a === cur.a);
if(index === -1) {
acc.push(cur);
} else {
acc[index] = Object.assign(acc[index], cur);
}
return acc;
}, []);
```
这段代码中,reduce的初始值为一个空数组。在每次遍历数组时,使用findIndex方法查找是否已经有相同key的对象存在,如果不存在则将当前对象直接添加到数组中,如果存在则使用Object.assign方法将两个对象合并在一起,并替换原来的数组元素。最终返回合并后的对象数组。
let arr = [{a:'xinxin'}, {a:'pipi'}, {a:'zhazha'}, {a:'xinxin', c:1}];合并相同的可以
用reduce方法实现,遍历数组中的每个元素,如果已经在结果数组中存在相同的元素,则将其属性合并,否则将其添加到结果数组中。
代码如下:
```
let arr = [{a:'xinxin'}, {a:'pipi'}, {a:'zhazha'}, {a:'xinxin', c:1}];
let result = arr.reduce((acc, curr) => {
let existing = acc.find(item => item.a === curr.a);
if (existing) {
Object.assign(existing, curr);
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result);
```
输出结果为:
```
[{a: "xinxin", c: 1}, {a: "pipi"}, {a: "zhazha"}]
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)