I have the following problem to concat multiple object values into one Array!
My current code:
const coins = [];
Object.keys(prices).forEach((key) => {
coins.push(prices[key]);
console.log("prices", prices);
console.log("prices[key]", prices[key]);
console.log("coins", coins);
});
Output:
prices { ETH: { USD: 1332.03 }, BTC: { USD: 14602.09 } }
prices[key] { USD: 1332.03 }
coins [ { USD: 1332.03 } ]
prices { ETH: { USD: 1332.03 }, BTC: { USD: 14602.09 } }
prices[key] { USD: 14602.09 }
coins [ { USD: 1332.03 }, { USD: 14602.09 } ]
What needs to be achieved:
coins = [ 1339.64, 14617.95 ]
I only need the values to do mathematical operations with them.
Pushing the USD
property would do:
coins.push(prices[key].USD);
But you can do it better:
Object.values(prices).map(price => price.USD);
As stated in the comments, push the USD price in instead of the whole object:
const coins = []; const prices = { ETH: { USD: 1332.03 }, BTC: { USD: 14602.09 } }; Object.keys(prices).forEach((key) => { coins.push(prices[key].USD); /* <- here is the change, add the key of the price */ console.log("prices", prices); console.log("prices[key]", prices[key]); console.log("coins", coins); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.