Home > Net >  How can I convert array to an object
How can I convert array to an object

Time:09-24

I have an array with a single element that looks like this [{…}]

All I have to do simply to convert this to an object like this {}

CodePudding user response:

I think the answer you are looking for is something like this:

const arr = [
  {name: 'name', value: 1},
  {name: 'name2', value: 2},
  {name: 'name3', value: 3},
  {name: 'name4', value: 4},
  {name: 'name5', value: 5},
]

const arrToObj = arr.reduce((obj, el) => {
  obj[el.name] = el.value
  return obj
}, {})

console.log(arrToObj)

CodePudding user response:

Solution was array.reduce((acc, x) => ({...acc,...x}))

  • Related