JavaScript Create map from Array


The Map object is a powerful data structure that allows you to store key-value pairs. While creating a Map from scratch is straightforward, there are times when you may need to convert an array into a Map for easier data manipulation and retrieval.

In this article, we will explore how to create a Map from an array in JavaScript.


Creating a Map from an Array of Arrays

Map is a built-in object in JavaScript that allows you to store key-value pairs. It is similar to an object, but the key can be of any type, not just a string or symbol.

Let's say we have an array of arrays, where each sub-array contains two elements: a key and a value. We want to convert this array into a Map object.

The following code snippet shows how to create a Map from an array of arrays:

Example

const arr = [
  ['name', 'John'],
  ['age', 25],
  ['occupation', 'Software Engineer']
];

// create a Map from the array
const map = new Map(arr);

// print the Map object
for (let [key, value] of map) {
  console.log(key, value);
}

Creating a Map from an Array of Objects

All the real world data is stored generally in the form of objects. So, it is very common to have an array of objects.

Here is an example of an array of objects:

Example

const arr = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 22 },
  { name: 'Jack', age: 27 }
];

// create a Map from the array
const map = new Map(arr.map(obj => [obj.name, obj.age]));

// print the Map object
for (let [key, value] of map) {
  console.log(key, value);
}

Using the set() method with forEach()

The set() method of the Map object adds or updates an element with a specified key and value to the Map object.

Suppose we have an array of objects, and we want to create a Map from it. We can use the set() method with forEach() to add each element of the array to the Map object.

Example

const arr = [
  ['name', 'John'],
  ['age', 25],
  ['occupation', 'Software Engineer']
];

// create a Map from the array
const map = new Map();
arr.forEach(([key, value]) => map.set(key, value));

// print the Map object
for (let [key, value] of map) {
  console.log(key, value);
}

Conclusion

Creating a Map from an array in JavaScript can be useful when you have data in an array format and need to perform operations that are more efficient with a Map data structure.

By leveraging the Map constructor and iterating over the array, you can easily convert the array into a Map with key-value pairs.

Now you have the knowledge to efficiently convert arrays into Map objects in JavaScript.