Converting array of objects to an object of objects in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of objects like this −

const arr = [{id:1,name:"aa"},{id:2,name:"bb"},{id:3,name:"cc"}];

We are required to write a JavaScript function that takes in one such array and returns an object of the object where the key of each object should be the id property.

Therefore, the output should look like this −

const output = {1:{name:"aa"},2:{name:"bb"},3:{name:"cc"}};

Notice that the id property is used to map the sub-objects is deleted from the sub-objects themselves.

Example

The code for this will be −

const arr = [{id:1,name:"aa"},{id:2,name:"bb"},{id:3,name:"cc"}];
const arrayToObject = arr => {
   const res = {};
   for(let i = 0; i < arr.length; i++){
      const key = arr[i]['id'];
      res[key] = arr[i];
      delete res[key]['id'];
   };
   return res;
};
console.log(arrayToObject(arr));

Output

And the output in the console will be −

{ '1': { name: 'aa' }, '2': { name: 'bb' }, '3': { name: 'cc' } }
raja
Published on 20-Nov-2020 10:12:12
Advertisements