Convert JS array into an object - JavaScript


Suppose, we have an array of objects like this −

const arr = [
   {id: 1, name: "Mohan"},
   {id: 2,name: "Sohan"},
   {id: 3,name: "Rohan"}
];

We are required to write a function that takes one such array and constructs an object from it with the id property as key and name as value

The output for the above array should be −

const output = {1:{name:"Mohan"},2:{name:"Sohan"},3:{name:"Rohan"}}

Example

Following is the code −

const arr = [
   {id: 1, name: "Mohan"},
   {id: 2,name: "Sohan"},
   {id: 3,name: "Rohan"}
];
const arrayToObject = arr => {
   const res = {};
   for(let ind = 0; ind < arr.length; ind++){
      res[ind + 1] = {
         "name": arr[ind].name
      };
   };
   return res;
};
console.log(arrayToObject(arr));

Output

This will produce the following output in console −

{
   '1': { name: 'Mohan' },
   '2': { name: 'Sohan' },
   '3': { name: 'Rohan' }
}

Updated on: 18-Sep-2020

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements