This post will discuss how to convert an array of objects to a Map in JavaScript.

There are several ways to convert an array to a map in JavaScript, depending on the type and structure of the array. Here are some of the methods that we can use, along with some examples:

1. Using Array.map() function

If we have an array of objects, where each object has a key and a value property, we can use the Array.map() function to transform the objects into arrays of key-value pairs, and then pass them to the Map() constructor, which creates a new map from an iterable of key-value pairs. For example, to convert an array of objects to a map with the name property of each object as the key and the age property as the value, we can write:

Download  Run Code

2. Using Map.set() function

Another way is to loop over the array of objects using the Array.forEach() function and then add each key-value pair from the array to a new map using the Map.set() function. We can choose any property of the element as the key and any value as the value for the map. For example, using the same array as before, we can do this:

Download  Run Code

3. Using Array.reduce() function

A third way is to use the Array.reduce() function to iterate over the array of objects and accumulate a plain object with the key-value pairs, and then pass that to the Map() constructor. For example, using the same array as before, the following code will create a plain object with the name property of each object as the property name and the age property as the value, and then convert it to a map using the Object.entries() function.

Download  Run Code

4. Convert two-dimensional array

If we have a two-dimensional array, where each subarray contains two elements that represent a key and a value, we can use the Map() constructor directly to convert it to a map. The following code illustrates this:

Download  Run Code

5. Convert one-dimensional array

If we have a one-dimensional array, where each element is a primitive value, such as a number or a string, we can use the Array.forEach() function or the Array.reduce() function to iterate over the array and add each element as a key or a value to a new map. The following code illustrates this:

Download  Run Code

That’s all about converting an array of objects to a Map in JavaScript.