How to convert Map Keys to an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by freestocks

Convert Map Keys to an Array #

To convert the keys of a Map to an array:

  1. Call the keys() method on the Map to get an iterator object that contains all of the keys in the Map.
  2. Call the Array.from() method, passing it the iterator as a parameter. The Array.from method creates a new array from an iterable object.
index.js
const map = new Map(); map.set('name', 'John'); map.set('age', 30); const keys = Array.from(map.keys()); console.log(keys); // ๐Ÿ‘‰๏ธ ['name', 'age'] console.log(keys.length); // ๐Ÿ‘‰๏ธ 2

We used the Map.keys method to get an iterator object containing the keys of the Map.

We passed the iterator as the only parameter to the Array.from method.

The Array.from method converts the iterable into an array and returns the new array instance.

This is the recommended approach when using TypeScript, because the compiler often complains when using the spread operator (...) with iterators.

An alternative approach is to use the spread operator (...).

Convert Map Keys to an Array using spread operator #

To convert the keys of a Map object to an array:

  1. Call the keys() method on the Map to get an iterator object that contains the keys of the Map.
  2. Use the spread operator (...) to unpack the values from the iterator into a new array.
index.js
const map = new Map(); map.set('name', 'John'); map.set('age', 30); const keys = [...map.keys()]; console.log(keys); // ๐Ÿ‘‰๏ธ ['name', 'age'] console.log(keys.length); // ๐Ÿ‘‰๏ธ 2

We used the spread operator to include all of the Map's keys into a new array.

This is the most commonly used approach when converting the keys of a Map into an array.

You could also do this with multiple Maps.

index.js
const map1 = new Map(); map1.set('name', 'John'); map1.set('age', 30); const map2 = new Map(); map2.set('country', 'Chile'); const keys = [...map1.keys(), ...map2.keys()]; console.log(keys); // ๐Ÿ‘‰๏ธ ['name', 'age', 'country'] console.log(keys.length); // ๐Ÿ‘‰๏ธ 3

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