我有一个对象数组,我想将每个价格值与最后价格相加作为新值,这是我的数据与最终数据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}]
除了
let prevPrice = 0
let prevVolume = 0
data.forEach(d => { prevPrice += d.price; prevVolume += d.volume;
d.price = prevPrice;
d.volume = prevVolume;
return d;
})
您可以使用
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);