To convert Map Keys to Array in JavaScript, there are 3 main methods that are 1 or 2 liner code. They will return the keys in an array in the same order during the creation of Map
.
Methods to Convert Map Keys to Array
Array.from()
Method- Spread Operator/Syntax (
...
) Method Array.prototype.forEach()
Method
The first 2 methods will make use of Map.prototype.keys() method from Map built-in object to get an iterator object holding onto the keys in insertion order.
Array.from()
Method
Array.from()
is a static method that will create a new array shallow copying the objects from any iterable objects including the return object from Map.prototype.keys(). This method is easy to use if all datatype of Keys are primitive.
In the example below, we will pass in the keys iterable, then the result will be a new array containing all keys in the same order.
const ageMap = new Map([ ['Person1', 11], ['Person2', 33], [10000001, 11] ]); const result = Array.from(ageMap.keys()); console.log(result); // ["Person1", "Person2", 10000001]
Spread Operator/Syntax (...
) Method
Base on the official documentation of Spread Syntax, we can see that it can expand any iterable. Thus, we can make use of its mechanism to spread out into an array object.
In the example below, we spread the Map
keys iterable object into an array.
const ageMap = new Map([ ['Person1', 11], ['Person2', 33], [10000001, 11] ]); const result = [...ageMap.keys()]; console.log(result); // ["Person1", "Person2", 10000001]
Array.prototype.forEach()
Method
From this guide, we know that forEach()
will not return any result. Hence, we will create a new array before executing the method.
In the example below, we will push the Keys every iteration to the result array.
const ageMap = new Map([ ['Person1', 11], ['Person2', 33], [10000001, 11] ]); const result = []; ageMap.forEach((value, key) => result.push(key)); console.log(result); // ["Person1", "Person2", 10000001]
Conclusion
We look into the 3 methods of converting Map Keys to array in JavaScript.
Array.from()
and the spread operator are the easiest to implement when the datatype inside Map Keys are all primitive type.
Array.prototype.forEach()
method will be good if you want to perform some operation like deep cloning or other operation every iteration with the key.
No Responses Yet