How to Convert an Array to a Map in JavaScript

In this article, we’ll be looking at two ways to quickly convert an array of objects to a Map object in JavaScript.

Scammers and spammers hate Aura - and that's a good thing for you

Aura logo
Are you tired of unwanted emails, texts, and calls from scammers and spammers? Aura uses cutting-edge AI technology to scan the internet to identify where your personal information is exposed and being sold. With Aura, you can take control of your online privacy and secure your personal information. Reduce robocalls and keep your information safe from identity thieves. Try Aura free for 2 weeks and see if your information has been compromised.

1. Map() Constructor and Array map()

To convert an array of objects to a map, we can use the Array map() method to create an array of key-value pairs, and then pass the resulting array to a Map() constructor to create a Map object.

const arr = [
  { key: 'user1', value: 'John' },
  { key: 'user2', value: 'Kate' },
  { key: 'user3', value: 'Peter' },
];
const map = new Map(arr.map((obj) => [obj.key, obj.value]));

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);

In the callback passed to the map() method, we return an array containing the key and the value for each object. This will result in an array of key-value pairs:

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(arr.map((obj) => [obj.key, obj.value]));

The Map constructor can take an array of this form as an argument to create a Map object.

2. Map set() and Array forEach()

Another way to convert an array of objects to a map is with the Array forEach() method. First, we create a new Map object. Then, we add entries for all the array elements to the Map, by calling the Map set() method in the callback passed to forEach(). Here’s an example:

const arr = [
  { key: 'user1', value: 'John' },
  { key: 'user2', value: 'Kate' },
  { key: 'user3', value: 'Peter' },
];

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

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.


Leave a Comment

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