4 回答
TA贡献1757条经验 获得超8个赞
初始架构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)
这是forEach
const 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)
TA贡献1826条经验 获得超6个赞
这是你想要的吗?
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})
TA贡献1789条经验 获得超10个赞
您可以采用动态方法来汇总对象的所有属性。
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);
TA贡献1842条经验 获得超12个赞
尝试这样:
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函数时,初始值被构造为要返回的最终对象。这些数字在回调函数中进行求和,然后返回结果。
添加回答
举报