javascript convert array of objects to object code example

Example 1: js array into object

const names = ['Alex', 'Bob', 'Johny', 'Atta'];

// convert array to th object
const obj = Object.assign({}, names);

// print object
console.log(obj);

// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}

Example 2: 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 3: how to convert an array into an object using javascript

// This function counts instances of elements in an array
// the return object has the array elements as keys
// and number of occurrences as it's value
const arrToInstanceCountObj = arr => arr.reduce((obj, e) => {
  obj[e] = (obj[e] || 0) + 1;
  return obj;
}, {});

arrToInstanceCountObj(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'])
/*
  {
    h: 1,
    e: 1,
    l: 3,
    o: 2,
    w: 1,
    r: 1,
    d: 1,
  }
*/