数组对象求和问题,在项目中有时会遇到列表求和的情况,这里记录一下。
1 2 3 4 5
| 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 }, ];
|
利用 reduce()和 Object.keys()
1 2 3 4 5 6 7 8 9 10 11
| 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);
|