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 have a few methods to do this that are described below:
- Javascript array.from()
- Javascript [ …Map.keys() ] method
Approach 1:
- 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 array.from() method to get the keys of the Map in the array.
html
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> How to convert Map keys to array in JavaScript ? </h3> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); let myMap = new Map().set('GFG', 1).set('Geeks', 2); up.innerHTML = 'myMap = ("GFG" => 1, "Geeks" => 2)'; function GFG_Fun() { var array = Array.from(myMap.keys()); down.innerHTML = "Elements in array are " + array + " and Length of array = " + array.length; } </script></body> |
Output:

Approach 2:
- 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.
html
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> How to convert Map keys to array in JavaScript </h3> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); let myMap = new Map().set('GFG', 1).set('Geeks', 2); up.innerHTML = 'myMap = ("GFG" => 1, "Geeks" => 2)'; function GFG_Fun() { var array = [ ...myMap.keys() ]; down.innerHTML = "Elements in array are " + array + " and Length of array = " + array.length; } </script></body> |
Output:







Please Login to comment...