Convert Array To Map in JavaScript

Convert Array To Map in JavaScript | For convenience or efficiency benefits, it can be good to occasionally transform an array into a map. But how can we do that in a way that makes the final code simple to understand?

The data structure where a value may be accessed using a unique key is referred to as a “map” in this context. Although objects can be used as maps in JavaScript, there is also a unique Map type with various benefits and drawbacks compared to utilizing objects. This article will discuss Map in a bit of detail.

Say we have several projects we wish to organize by month of completion. We may need to do this if we frequently access projects from a particular month and don’t want to go through the array each time or use React/Vue/Svelte to render the projects into month components.

We can accomplish this in a few different ways. We will first examine how to achieve this using the Array.reduce() method before discussing how to simplify things using for..of.

Convert Array To Map in JavaScript – Constructor Map() and map array()

We may use the Array map() method to produce an array of key-value pairs from an array of objects and then provide that array to the Map() constructor to create a Map object.

const arr = [
  { key: "user1", value: "Alex" },
  { key: "user2", value: "Sid" },
  { key: "user3", value: "Rick" },
];

const map = new Map(arr.map((obj) => [obj.key, obj.value]));

console.log(map);

Output:-

Map(3) { ‘user1’ => ‘Alex’, ‘user2’ => ‘Sid’, ‘user3’ => ‘Rick’ }

Convert Array To Map in JavaScript Using forEach() & set() 

Another technique to transform an array of items into a map is with the Array forEach() function. We start by making a new Map object. Then, we execute the Map set() method in the callback supplied to forEach to add entries for each array element to the Map (). Here’s an illustration:-

const arr = [
  { key: "user1", value: "Alex" },
  { key: "user2", value: "Sid" },
  { key: "user3", value: "Rick" },
];

const map = new Map();
arr.forEach((obj) => {
  map.set(obj.key, obj.value);
});

console.log(map);

Output:-

Map(3) { ‘user1’ => ‘Alex’, ‘user2’ => ‘Sid’, ‘user3’ => ‘Rick’ }

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *