-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
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Luke Tan
  • 2,048
  • 2
  • 13
  • 21

2 Answers2

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
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);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62