how to convert array of objects into an object in javascript code example

Example 1: javascript Convert an array of objects to a single object

const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});

// Example
toObject(
    [
        { id: '1', name: 'June', gender: 'Female' },
        { id: '2', name: 'Alex', gender: 'Male' },
        { id: '3', name: 'Harry', gender: 'Male' },
    ],
    'id'
);
/* 
{
    '1': { id: '1', name: 'June', gender: 'Female' },
    '2': { id: '2', name: 'Alex', gender: 'Male' },
    '3': { id: '3', name: 'Harry', gender: 'Male' },
}
*/

Example 2: convert array to object javascript

const convertArrayToObject = (array, key) =>
  array.reduce(
    (obj, item) => ({
      ...obj,
      [item[key]]: item
    }),
    {}
  );