Skip to content
Advertisement

How do i convert an array of objects to objects of objects?

I have an array of objects

const data = [
  { id: 1, name: "A", condition: true },
  { id: 4, name: "B", condition: false },
  { id: 7, name: "C", condition: true },
  { id: 11, name: "D", condition: true },
  { id: 12, name: "E", condition: false }
]


Sample output

const data = {
  0 : { id: 1, name: "A", condition: true },
  1 : { id: 4, name: "B", condition: false },
  2 : { id: 7, name: "C", condition: true },
  3 : { id: 11, name: "D", condition: true },
  4 : { id: 12, name: "E", condition: false }
}

I tried this way but did not get the correct keys, not sure how do i get proper keys in ascending order.

const arrayToObject = {
     return data.reduce((obj, item) => {
         obj[item['id]] = item
         return obj
     }, {})
 }

Advertisement

Answer

Use Object.assign

const data = [
  { id: 1, name: "A", condition: true },
  { id: 4, name: "B", condition: false },
  { id: 7, name: "C", condition: true },
  { id: 11, name: "D", condition: true },
  { id: 12, name: "E", condition: false }
]

const res = Object.assign({}, data);

console.log(res)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement