 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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' } }Advertisements
 