Convert an Array of Objects to a Map in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

banner

Photo by Tamara Bellis

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 in the array.

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

The map method returns the array of key-value pairs.

index.js
// [['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 in the array.

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

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

After the last iteration, the Map will contain all key-value pairs from the object.

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 and we don't have to create an intermediary variable.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee