Friday, October 24, 2025
HomeLanguagesJavascriptHow to convert Map keys to an array in JavaScript ?

How to convert Map keys to an array in JavaScript ?

In this article, we are given a Map and the task is to get the keys of the map into an array using JavaScript. We can access the keys by using the Map keys() method.

We have a few methods to do this that are described below:

 Approach 1: Using array.from() Method

  • Declare a new map object
  • Display the map content
  • Use the keys() method on Map Object to get the keys of Map.
  • Then use the array.from() method to convert a map object to an array.

Example 1: This example uses an array.from() method to get the keys of the Map in the array. 

Javascript




let myMap = new Map().set('GFG', 1).set('Geeks', 2);
let array = Array.from(myMap.keys());
 
//Return the length of array
console.log(array.length);


Output

2

Approach 2: Using [ …Map.keys() ] Method

  • Declare a new map object
  • Display the map content
  • Use the [ …myMap.keys() ] method on Map Object to get the keys of Map as an array.

Example 2: This example uses the [ …Map.keys() ] method to get the keys of the Map in the array. 

Javascript




let myMap = new Map().set('GFG', 1).set('Geeks', 2);
let array = [...myMap.keys()];
 
//return the length of array
console.log(array.length);


Output

2

Approach 3: Using for…of Loop Method

  • Create an empty array
  • By using the for…of Loop, we can iterate over the keys
  • At each iteration, we can push the key into an array.

Example:

Javascript




let myMap = new Map().set('GFG', 1).set('Geeks', 2).set('Geeksforneveropen',3);
let arr =[];
for (let key of myMap.keys()) {
    arr.push(key);
}
console.log(arr);


Output

[ 'GFG', 'Geeks', 'Geeksforneveropen' ]

Approach 4: Using Map.forEach() Method

  • Create an empty array
  • Use Map.forEach() method for iterating over the loop
  • then push the keys into an array

Example:

Javascript




let myMap = new Map().set('GFG', 1)
                      .set('Geeks', 2)
                      .set('Geeksforneveropen', 3);
let arr = [];
myMap.forEach((values, keys) => {
    arr.push(keys);
});
console.log(arr);


Output

[ 'GFG', 'Geeks', 'Geeksforneveropen' ]
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS