Search code examples
javascriptarraysobject

Converting array of objects into a single object


This is my initial array:

[ 
   { 
    id: 1,
    name: 'pos',
    code: 'pos123',
    appCode: 22,
   },
  { 
    id: 2,
    name: 'tailor',
    code: 'tailor123',
    appCode: 21,
  } 
]

My desired output:

{
   pos123: {
    id: 1,
    name: 'pos',
    code: 'pos123',
    appCode: 22,
  },
  tailor123: {
    id: 2,
    name: 'tailor',
    code: 'tailor123',
    appCode: 21,
  },
}

I tried doing this with map, but I couldn't figure it out. Should I be using reduce here?


Solution

  • Your output is not an array - it's an object, so you have to use reduce. You can only use map to turn X number of items in an array into X number of items in another array.

    const input=[{id:1,name:'pos',code:'pos123',appCode:22,},{id:2,name:'tailor',code:'tailor123',appCode:21,}]
    const output = input.reduce((a, obj) => {
      a[obj.code] = obj;
      return a;
    }, {});
    console.log(output);