I have a collection of objects like this:
"stock": [
{
"Quantity": -36,
"Price": 74.55,
"Consideration": 2683.8,
"Direction": "SELL"
},
{
"Quantity": -50,
"Price": 74.14,
"Consideration": 3707,
"Direction": "SELL"
},
{
"Quantity": 12,
"Price": 77.15,
"Consideration": -925.8,
"Direction": "BUY"
},
{
"Quantity": 15,
"Price": 76.4,
"Consideration": -1146,
"Direction": "BUY"
},
{
"Quantity": 19,
"Price": 75.8,
"Consideration": -1440.2,
"Direction": "BUY"
},
{
"Quantity": 20,
"Price": 82.44,
"Consideration": -1648.8,
"Direction": "BUY"
},
{
"Quantity": 10,
"Price": 82.08,
"Consideration": -820.8,
"Direction": "BUY"
},
{
"Quantity": 10,
"Price": 82.49,
"Consideration": -824.9,
"Direction": "BUY"
}
]
I aim to deduct the PRICE attribute of each object from the previous one and include the result as profit in that preceding object...
So starting from the first object in the array, I will have;
74.55 - 74.14 and the outcome will be added to the second object as
profit: "result:
The only solution I can think of is this:
let stockData = stock.map((stock) => {
return {
Quantity: stock.Quantity,
Price: stock.Price,
Consideration: stock.Consideration,
Direction: stock.Direction,
};
});
for (let i = 0; i < stockData.length; i++) {
let profit = stockData[i].Price - stockData[i - 1].Price;
}
res.status(200).json({
stock: stockData,
});
However, when accessing stockData[i - 1].Price, I encounter the error "can not read property Price of undefined"