js 遍历list,把拥有相同id的对象合并,剩余的参数值组成一个数组
时间: 2024-01-04 09:04:04 浏览: 39
可以使用 reduce 方法来实现这个需求。首先,我们需要定义一个空对象作为 reduce 方法的初始值。然后,遍历 list 数组中的每一个元素,如果该元素的 id 属性值在 reduce 对象中已经存在,则将该元素的其他属性值 push 到该 id 对应的数组中;否则,将该元素的 id 对应的属性值设置为一个新数组,并将该元素的其他属性值 push 到该数组中。最后,使用 Object.values 方法将 reduce 对象转换为一个数组即可。以下是示例代码:
```javascript
const list = [
{ id: 1, name: 'a', value: 10 },
{ id: 2, name: 'b', value: 20 },
{ id: 1, name: 'c', value: 30 },
{ id: 3, name: 'd', value: 40 },
{ id: 1, name: 'e', value: 50 },
];
const merged = Object.values(list.reduce((acc, cur) => {
if (acc[cur.id]) {
acc[cur.id].values.push(cur.value);
} else {
acc[cur.id] = { id: cur.id, name: cur.name, values: [cur.value] };
}
return acc;
}, {}));
console.log(merged);
// Output: [
// { id: 1, name: 'a', values: [10, 30, 50] },
// { id: 2, name: 'b', values: [20] },
// { id: 3, name: 'd', values: [40] }
// ]
```
在上面的代码中,我们将 list 数组作为 reduce 方法的初始值,遍历 list 数组中的每一个元素,并将元素的 id 属性值作为 reduce 对象的属性名,该属性的值为一个对象,包含 id、name 和 values 三个属性。如果 reduce 对象中已经存在该元素的 id 属性值,则将该元素的 value 属性值 push 到该属性值的 values 数组中;否则,将该元素的 id、name 和一个包含 value 属性值的数组作为该属性值的值。最后,使用 Object.values 方法将 reduce 对象转换为一个数组即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)