将每个价格与之前的值相加作为React js中的新值

问题描述 投票:0回答:2

我有一个对象数组,我想将每个价格值与最后价格相加作为新值,这是我的数据与最终数据I

data=[{price: 2, volume: 123}
{price: 3, volume: 123}
{price: 4, volume: 254}
{price: 1, volume: 444}
{price: 5, volume: 555}]

finalfata=[{price: 2, volume: 555}
1: {price: 5, volume: 777}
2: {price: 9, volume: 5000}
3: {price: 10, volume: 8000}
4: {price: 15, volume: 4000}]

除了

arrays object sum reduce
2个回答
0
投票
let prevPrice = 0
let prevVolume = 0
data.forEach(d => { prevPrice += d.price; prevVolume += d.volume; 
    d.price = prevPrice; 
    d.volume = prevVolume;
    return d;
})

0
投票

您可以使用

reduce
将价格与前一个价格相加,并根据这些结果创建一个新数组:

const data = [ 
{price: 2, volume: 123},
{price: 3, volume: 123},
{price: 4, volume: 254},
{price: 1, volume: 444},
{price: 5, volume: 555}
];

const finalData = data.reduce((tot, each) => 
  [...tot, { ...each, price: each.price + (tot.at(-1) || { price: 0 }).price }]
, []);

console.log(finalData);

© www.soinside.com 2019 - 2024. All rights reserved.