I am trying to do addition of the currency prices which i am getting as an array of objects. But each time i receive this data, currency type can differ between 3 and stays same in the whole array of objects.
My problem here is that when i try to do the addition idk about the key beforehand which key(currency_type) it is. I have tried an approach using map and OR operator.
Here is the controller:
const getHistorycalPrices = async (req: IGetHistorycalPricesRequest, res: IGetHistorycalPricesResponse) => {
try {
if (!req.query.currency) {
res.status(400).send({
success: false,
message: "Could not get historycal prices",
});
return;
}
// Gets currency column by query from crypto DB table
const allPrices = await Crypto.findAll({ attributes: [req.query.currency, 'createdAt'], order: [['createdAt', 'DESC']] });
if (!allPrices) {
res.status(400).send({
success: false,
message: "Could not get historycal prices",
});
return;
}
// Get first row from crypto DB table
const firstRowPrices = await Crypto.findByPk(1);
if (!firstRowPrices) {
res.status(400).send({
success: false,
message: "Could not get first row prices",
});
return;
}
res.status(200).send({
success: true,
message: "Successfully retrieved historycal prices",
data: allPrices.map((price) => ({
cryptoPrices: (+price.BTCUSD + +firstRowPrices.BTCUSD).toString() ||
(+price.ETHUSD + +firstRowPrices.ETHUSD).toString() ||
(+price.LTCUSD + +firstRowPrices.LTCUSD).toString(),
createdAt: price.createdAt.toDateString(),
})),
});
return;
} catch (e) {
res.status(500).send({
success: false,
message: "Server error",
});
return;
}
};
Right now when I'm sending the data if it's the first line I'll get -
But if it's the ETHUSD OR the LTCUSD I'll get -
There is a problem with my OR operator in the allPrices.map but I can't understand what it is.
You can use the Optional chaining operator(?.).
allPrices.map((price) => ({
cryptoPrices: (+price?.BTCUSD + +firstRowPrices?.BTCUSD ||
+price?.ETHUSD + +firstRowPrices?.ETHUSD ||
+price?.LTCUSD + +firstRowPrices?.LTCUSD).toString(),
createdAt: price.createdAt.toDateString(),
})),
});
Another way: Instead of OR operator, try using the ternary operator.
allPrices.map((price) => ({
cryptoPrices:(("BTCUSD" in price)?(+price.BTCUSD + +firstRowPrices.BTCUSD):
("ETHUSD" in price)?(+price.ETHUSD + +firstRowPrices.ETHUSD):
(+price.LTCUSD + +firstRowPrices.LTCUSD)).toString(),
createdAt: price.createdAt.toDateString(),
})),
});