How to Convert an Array to Map in JavaScript

Here are two ways to convert an Array to a Map in JavaScript.

  1. Using Array.map() method with Map() constructor
  2. Using Map set() and Array forEach() methods

Method 1: Array.map() method and Map()

Pictorial Representation of Array.map() method and Map()

Using the Array.prototype.map() method, you can convert an array of objects into an array of key-value pairs and then pass that to the Map constructor.

If you have an array of objects, you want to create a Map with the id property as the key and the entire object as the value.

const data = [
  { id: 1, name: 'Dhaval', age: 30 },
  { id: 2, name: 'Niva', age: 28 },
  { id: 3, name: 'Vidisha', age: 01 },
];

const dataMap = new Map(data.map(element => [element.id, element]));

console.log(dataMap);

Output

Map(3) {
  1 => { id: 1, name: 'Dhaval', age: 30 },
  2 => { id: 2, name: 'Niva', age: 28 },
  3 => { id: 3, name: 'Vidisha', age: 01 }
}

In this example, we used the array.map() method to create a new array of key-value pairs, where each pair is an array with two elements: the id property and the object itself. Then, we passed this new array to the Map constructor to create a Map.

Method 2: Map set() and Array forEach()

Pictorial representation of Using Map set() and Array forEach() methods

If you have an array of objects and you want to convert it into a map where each object becomes a key-value pair in the map, you can use the “Array.prototype.forEach()” method.

const users = [
 { id: 1, name: 'Alice' },
 { id: 2, name: 'Bob' },
 { id: 3, name: 'Charlie' }
];

const userMap = new Map();

users.forEach(user => {
 userMap.set(user.id, user);
});

console.log(userMap);

Output

Map(3) {
  1 => { id: 1, name: 'Alice' },
  2 => { id: 2, name: 'Bob' },
  3 => { id: 3, name: 'Charlie' }
}

This is a clean and effective way to convert an array of objects into a map based on a specific property of the object.

That’s it!