

- 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
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 Questions & Answers
- 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
- Map object in JavaScript.
- How to use my object like an array using map function in JavaScript?
- Reduce array in JavaScript
- Implementing MongoDB map-reduce
- Object to Map conversion in JavaScript
- How to convert array to object in JavaScript
- Convert array of object to array of array in JavaScript
- Convert object of objects to array in JavaScript
- Convert object to array of objects in JavaScript
- MongoDB query to fetch random value using Map Reduce concept.
- JavaScript: How to map array values without using "map" method?
- Convert an object to another type using map() method with Lambda in Java?
Advertisements