-
陪伴而非守候
初始架构Array.reduce实际上取决于您。const data = [{ number_1: 10, number_2: 20 }, { number_1: 15, number_2: 5 }, { number_1: 15, number_2: 35 },];const res = data.reduce((acc, { number_1, number_2}) => { acc.sum_number_1 += number_1; acc.sum_number_2 += number_2; return acc;}, { sum_number_1: 0, sum_number_2: 0})console.log(res)这是forEachconst data = [{ number_1: 10, number_2: 20 }, { number_1: 15, number_2: 5 }, { number_1: 15, number_2: 35 },];const res = { sum_number_1: 0, sum_number_2: 0};data.forEach(({ number_1, number_2}) => { res.sum_number_1 += number_1; res.sum_number_2 += number_2;})console.log(res)
-
跃然一笑
这是你想要的吗?data.reduce((acc, {number_1, number_2}) => { acc.sum_number_1 += number_1; acc.sum_number_2 += number_2; return acc;},{sum_number_1: 0, sum_number_2: 0})
-
至尊宝的传说
您可以采用动态方法来汇总对象的所有属性。const data = [{ number_1: 10, number_2: 20 }, { number_1: 15, number_2: 5 }, { number_1: 15, number_2: 35 }], result = data.reduce((r, o) => { Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v) return r; });console.log(result);
-
红颜莎娜
尝试这样:data = [ { number_1: 10, number_2: 20 }, { number_1: 15, number_2: 5 }, { number_1: 15, number_2: 35 },];const reducer = (accumulator, currentValue) => { accumulator.sum_number_1 += currentValue.number_1; accumulator.sum_number_2 += currentValue.number_2; return accumulator;};console.log(data.reduce(reducer, { sum_number_1: 0, sum_number_2: 0 }));使用reduce函数时,初始值被构造为要返回的最终对象。这些数字在回调函数中进行求和,然后返回结果。