Convert JS array into an object - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' }
}
raja
Published on 18-Sep-2020 13:19:56
Advertisements