Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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