-1

I have an array that looks like this:

const myArray = [
  { 'John': 50 },
  { 'Adam': 29 },
  { 'Jack': 40 }
]

How do I convert the array into an object that looks like this?

const convertedObject = {
  'John': 50,
  'Adam': 29,
  'Jack': 40
}
1
  • Start with an empty object and use Object.assign on it several times. Commented Jul 24, 2018 at 7:21

2 Answers 2

2

You can spread the array into Object.assign():

const myArray = [
  { 'John': 50 },
  { 'Adam': 29 },
  { 'Jack': 40 }
]

const convertedObject = Object.assign({}, ...myArray)

console.log(convertedObject)

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this leads to a stack overflow on arrays that are large enough.
1

You can use Array.reduce() for that:

const myArray = [
    {'John':50},
    {'Adam':29},
    {'Jack':40}
]
var res = myArray.reduce((acc, item) => {
  var key = Object.keys(item)[0];
  acc[key] = item[key];
  return acc;
}, {});
console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.