Search code examples
javascriptarraysalgorithmobjectjavascript-objects

Transform javascript array of object to object with keys and array of values


I have an array of objects I need to transform into new objects. some value as keys and an array of values.

const data = [
  {
    type: 'user',
    id: 1
  },
  {
    type: 'user',
    id: 2
  },
  {
    type: 'group',
    id: 1
  },
  {
    type: 'group',
    id: 2
  },
  {
    type: 'user',
    id: 3
  },
  {
    type: 'user',
    id: 4
  }
]

and the desired result is

const result = {
  user: [1, 2, 3, 4],
  group: [1, 2]
}

what I've tried using reduced but it not what I'm expected.

const result = data.reduce((acc, { type, ...obj }) => {
  acc[type] = data.map(item => item.id)
  return acc;
}, {})

result = { user: [ 1, 2, 1, 2, 3, 4 ], group: [ 1, 2, 1, 2, 3, 4 ] }

Solution

  • Each iterate, you check if the accumulate object has the type, if yes, push the iterated element's id to the existing array, else init the array

    const data = [
      {
        type: "user",
        id: 1,
      },
      {
        type: "user",
        id: 2,
      },
      {
        type: "group",
        id: 1,
      },
      {
        type: "group",
        id: 2,
      },
      {
        type: "user",
        id: 3,
      },
      {
        type: "user",
        id: 4,
      },
    ]
    
    const res = data.reduce((acc, el) => {
      if (acc[el.type]) {
        acc[el.type].push(el.id)
      } else {
        acc[el.type] = [el.id]
      }
    
      return acc
    }, {})
    
    console.log(res)