数组对象求和
数组对象求和问题,在项目中有时会遇到列表求和的情况,这里记录一下。
let list = [
{ id: 1, value1: 5, value2: 10, value3: 20 },
{ id: 2, value1: 15, value2: 10, value3: 50 },
{ id: 3, value1: 40, value2: 20, value3: 20 },
];
1
2
3
4
5
2
3
4
5
# 利用 reduce()和 Object.keys()
function mergeArr(arr, data) {
let result = arr.reduce((acc, cur) => {
Object.keys(acc).forEach((item) => (acc[item] += cur[item]));
return acc;
}, data);
return result;
}
const data = { value1: 0, value2: 0, value3: 0 };
mergeArr(list, data); // {value1: 60, value2: 40, value3: 90}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
上次更新: 2022/09/06, 10:30:04