convert array of objects to object of objects 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
    }),
    {}
  );

Example 3: javascript convert array to object

function arrayToObject(arr) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i){
        obj[i] = arr[i];
    }
    return obj;
}
var colors=["red","blue","green"];
var colorsObj=arrayToObject(colors);//{0: "red", 1: "blue", 2: "green"}