kkkkkkkkkkkkkkkkk
kkkkkkkkkkkkkkkkk

Reputation: 728

How can I convert array to an object

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 {}

Upvotes: 0

Views: 106

Answers (2)

kkkkkkkkkkkkkkkkk
kkkkkkkkkkkkkkkkk

Reputation: 728

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

Upvotes: 0

Sinan Yaman
Sinan Yaman

Reputation: 5937

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)

Upvotes: 2

Related Questions