- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 2D array to object using map or reduce in JavaScript
Let’s say, we have a two-dimensional array that contains some data about the age of some people.
The data is given by the following 2D array
const data = [ ['Rahul',23], ['Vikky',27], ['Sanjay',29], ['Jay',19], ['Dinesh',21], ['Sandeep',45], ['Umesh',32], ['Rohit',28], ];
We are required to write a function that takes in this 2-D array of data and returns an object with key as the first element of each subarray i.e., the string and value as the second element.
We will use the Array.prototype.reduce() method to construct this object, and the code for doing this will be −
Example
const data = [ ['Rahul',23], ['Vikky',27], ['Sanjay',29], ['Jay',19], ['Dinesh',21], ['Sandeep',45], ['Umesh',32], ['Rohit',28], ]; const constructObject = arr => { return arr.reduce((acc, val) => { const [key, value] = val; acc[key] = value; return acc; }, {}); }; console.log(constructObject(data));
Output
The output in the console will be −
{ Rahul: 23, Vikky: 27, Sanjay: 29, Jay: 19, Dinesh: 21, Sandeep: 45, Umesh: 32, Rohit: 28 }
- Related Articles
- How to convert array into array of objects using map() and reduce() in JavaScript
- Convert object to a Map - JavaScript
- Sum 2D array in Python using map() function
- How to use my object like an array using map function in JavaScript?
- JavaScript: How to map array values without using "map" method?
- How to convert a 2D array to a CSV string in JavaScript?
- Convert array of object to array of array in JavaScript
- How to convert array to object in JavaScript
- Map object in JavaScript.
- Convert object of objects to array in JavaScript
- Convert object to array of objects in JavaScript
- Object to Map conversion in JavaScript
- Convert an object to another type using map() method with Lambda in Java?
- Reduce array in JavaScript
- How to convert a Map to JSON object using JSON-lib API in Java?

Advertisements