0

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.

2
  • 1
    You're pushing the object in, change to coins.push(prices[key].USD); Commented Jan 10, 2018 at 16:42
  • Actually, why is your desired result different figures? coins = [ 1339.64, 14617.95 ] you start with 1332.03 & 14602.09 Commented Jan 10, 2018 at 16:46

2 Answers 2

3

Pushing the USD property would do:

coins.push(prices[key].USD);

But you can do it better:

Object.values(prices).map(price => price.USD);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.