
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting array of objects to an object of objects in JavaScript
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' } }
- Related Questions & Answers
- Converting array of objects to an object in JavaScript
- JavaScript Converting array of objects into object of arrays
- How to transform object of objects to object of array of objects with JavaScript?
- Convert array of objects to an object of arrays in JavaScript
- Splitting an object into an array of objects in JavaScript
- Flat a JavaScript array of objects into an object
- Convert object of objects to array in JavaScript
- Convert object to array of objects in JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Convert an array of objects into plain object in JavaScript
- JavaScript: Sort Object of Objects
- Manipulating objects in array of objects in JavaScript
- Search from an array of objects via array of string to get array of objects in JavaScript
- Sorting an array of objects by an array JavaScript
- JavaScript: Converting a CSV string file to a 2D array of objects
Advertisements