Convert an Array of Objects to a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert an Array of Objects to a Map #

To convert an array of objects to a Map, call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

index.js
const arr = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; const map1 = new Map( arr.map(object => { return [object.key, object.value]; }), ); // ️👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map1);

The function we passed to the Array.map method gets called with each element (object) in the array.

On each iteration, we return an array containing the object's key and value.

The map() method returns an array of key-value pairs.

index.js
const arr = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; // 👇️ [['name', 'Tom'], ['country', 'Chile']] console.log( arr.map(object => { return [object.key, object.value]; }), );

The last step is to pass the result to the Map() constructor.

The Map() constructor takes an iterable object, such as an array, as a parameter and creates a new Map object. Note that the iterable must contain key-value pairs.

An alternative approach is to use the Array.forEach method.

To convert an array of objects to a Map:

  1. Use the Map() constructor to create a new Map.
  2. Call the forEach() method on the array.
  3. On each iteration, add the key-value pair to the new Map.
index.js
const arr = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; const map2 = new Map(); arr.forEach(object => { map2.set(object.key, object.value); }); // ️👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map2);

The function we passed to the forEach() method gets called with each element (object) in the array.

The forEach method returns undefined, so we have to declare a variable that will store the state.

On each iteration, we use the Map.set method to add a new key-value pair to the Map.

After the last iteration, the Map will contain all key-value pairs from the array of objects.

It's a matter of personal preference which approach you pick. I'd go with the Array.map method because it enables us to return an array of key-value pairs without having to create an intermediary variable.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.