JavaScript maps let us store key-value pairs easily in our code.
Sometimes, we may want to convert JavaScript map keys into an array.
In this article, we’ll look at how to convert JavaScript map keys into an array.
Array.from Method and Map.prototype.keys
We can call the Array.from
with the keys
method of a map to convert the keys of a map to an array.
The keys
method return an iterator with all the keys.
And the Array.from
method converts the iterator with keys into an array of keys.
For instance, we can write:
const map = new Map()
.set('a', 1)
.set('b', 2);
const keys = Array.from(map.keys());
console.log(keys)
We create a new Map
instance to create a map.
Then we call set
with the key and value that we want to set passed in in this order.
Next, we call Array.from
with the return value of map.keys
to return the iterator with the map keys to an array.
Therefore we get:
["a", "b"]
as the value of keys
.
Spread Operator and Map.prototype.keys
Likewise, we can use the spread operator with the keys
method to convert the iterator with keys to an array of keys.
For instance, we can write:
const map = new Map()
.set('a', 1)
.set('b', 2);
const keys = [...map.keys()];
console.log(keys)
And we get the same result for keys
.
Conclusion
We can return an iterator with the map keys with the Map.prototype.keys
method.
Then we can convert the iterator with keys to an array of keys either with the Array.from
method or the spread operator.