我试图自动计算每次单击获取数据的按钮时要获取的对象的总和,但是我不确定如何进行处理。
这是每次我单击按钮时都会获取数据的脚本:
createTrade (zoneId, cycleId) {
this.getTrade().then(trade => {
let zone = this.zones.find(zone => zone.id === zoneId);
zone.cycles.map(cycle => {
if (cycle.id === cycleId) {
return {...cycle, ...cycle.trades.push(Object.assign(trade, {
account: this.accounts.find(acc => acc.id === this.form.accountId)
}))}
}
console.log(this.trade.realizedPL);
return cycle;
});
this.form = {
accountId: "",
tradeId: null
};
}).catch(() => {
alert('Trade does not exist');
});
},
这是我能够拉出的物体。每当我单击按钮获取新数据时,我都想添加所有“ realizedPL”。
英语不是我的母语,因此,如果真的感到困惑,我感到抱歉。希望有人能帮助我。谢谢!
答案 0 :(得分:0)
这对于array.reduce是一个很好的例子。看起来像这样:
const totalRealizedPL => data.reduce(
(subtotal, item) => subtotal + item.realizedPL, // accumulator function
0 // initial value
);
// generate some data for demo purposes
const data = Array.from({length: 5}, () => ({ value: Math.floor(Math.random() * 100) }));
const sum = data.reduce((subtotal, item) => subtotal + item.value, 0);
console.log(sum);
console.log(data);