convert array to array of objects javascript 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: convert object to array javascript

var object = {'Apple':1,'Banana':8,'Pineapple':null};
//convert object keys to array
var k = Object.keys(object);
//convert object values to array
var v = Object.values(object);

Example 4: convert array to object javascript

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

Example 5: js create object from array

[
  { id: 10, color: "red" },
  { id: 20, color: "blue" },
  { id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})

//output: 
{red: 10, blue: 20, green: 30}

Example 6: js array to object with keys

const arr = ['a','b','c'];
const res = arr.reduce((a,b)=> (a[b]='',a),{});
console.log(res)

Tags:

Java Example