Estoy tratando de agregar los precios de las monedas que obtengo como una matriz de objetos. Pero cada vez que recibo estos datos, el tipo de moneda puede diferir entre 3 y permanece igual en toda la matriz de objetos.
Mi problema aquí es que cuando trato de hacer la adición idk sobre la clave de antemano qué clave (currency_type) es. He intentado un enfoque usando el mapa y el operador OR.
Aquí está el controlador:
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; } }; En este momento, cuando estoy enviando los data , si es la primera línea que obtendré:
Pero si es ETHUSD O LTCUSD , obtendré:
Hay un problema con mi operador OR en allPrices.map pero no puedo entender de qué se trata.
Puede usar el operador de encadenamiento opcional (?.) .
allPrices.map((price) => ({ cryptoPrices: (+price?.BTCUSD + +firstRowPrices?.BTCUSD || +price?.ETHUSD + +firstRowPrices?.ETHUSD || +price?.LTCUSD + +firstRowPrices?.LTCUSD).toString(), createdAt: price.createdAt.toDateString(), })), });Otra forma : en lugar del operador OR, intente usar el operador ternario.
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(), })), });