Convert 2D array to object using map or reduce in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
}
raja
Published on 25-Aug-2020 10:23:58
Advertisements