
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 Array to Object in JavaScript
Let’s say we need to convert the following array of array into array of objects with keys as English alphabet
const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
This can be done by mapping over the actual arrays and reducing the subarrays into objects like the below example −
Example
const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; const dataArr = data.map(arr => { return arr.reduce((acc, cur, index) => ({ ...acc, [String.fromCharCode(97 + index)]: cur }), Object.create({})) }); console.log(dataArr);
Output
The console output for this code will be −
[ { a: 1, b: 2, c: 3, d: 4 }, { a: 5, b: 6, c: 7, d: 8 }, { a: 9, b: 10, c: 11, d: 12 } ]
Advertisements