1

I have an array of objects and I want to push only the values of each object inside the array to a new object as a key value pair using Javascript.

eg:

const prices = [
  { ticker: 'msft', price: 14.3 },
  { ticker: 'msft', price: 10.2 },
  { ticker: 'ibm', price: 9.2 },
  { ticker: 'amzn', price: 10.2 },
]; 

Output should be as below:

{
"msft":[10.2,14.3],
"ibm":[9.2],
"amzn":[10.2]
}
3
  • Why does 10.2 come before 14.3? Commented Aug 30, 2022 at 18:40
  • 1
    What have you attempted to achieve this result? Where is that going wrong? Commented Aug 30, 2022 at 18:47
  • 2
    Please add the code you've attempted to your question as a minimal reproducible example. Commented Aug 30, 2022 at 18:57

1 Answer 1

1
const output = prices.reduce((result, object) => {
    const key = object.ticker;
    result[key] = result[key] || [];
    result[key].push(object.price);
    return result;
}, {})
Sign up to request clarification or add additional context in comments.

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.