Convert Map Keys To An Array In JavaScript

To convert map keys to an array in JavaScript, you can use any of these methods –

  1. Use Array.from() method on the map keys to get an array of the map keys.
  2. Use spread operator(…) with map keys to get an array of the map keys.
  3. Use for…of loop to get an array of the map keys.

Let’s discuss each of these methods in detail below.

convert map keys to array in javascript

Use Array.from() Method To Convert Map Keys To An Array In JavaScript

The Array.from() method creates a new array instance from an array-like or iterable object.

We can use this method on the map keys to get an array of the map keys as follows –

const map = new Map();

map.set('1', 'a');

map.set('2', 'b');

map.set('3', 'c');

const mapKeys = Array.from(map.keys());

console.log(mapKeys);

Output – [“1”, “2”, “3”]

In the above code, we have created a map with three key-value pairs.

We have used the map.keys() method to get an iterable object of the map keys.

Then we use the Array.from() method on the map keys to get an array of the map keys and store it in the mapKeys variable. Finally, we print out this array using console.log().

Use Spread Operator To Convert Map Keys To An Array In JavaScript

We can use the spread operator (…) with the map keys to get an array of the map keys as follows –

const map = new Map();

map.set('1', 'a');

map.set('2', 'b');

map.set('3', 'c');

const mapKeys = […map.keys()];

console.log(mapKeys);

Output – [“1”, “2”, “3”]

In the above code, we have created a map with three key-value pairs.

Then we use the spread operator (…) on the map keys to get an array of the map keys and store it in the mapKeys variable. Finally, we print out this array using console.log().

Use For…Of Loop To Convert Map Keys To An Array In JavaScript

We can use a for…of loop to get an array of the map keys as follows –

const map = new Map();

map.set('1', 'a');

map.set('2', 'b');

map.set('3', 'c');

const mapKeys = [];

for (let key of map.keys()) {

mapKeys.push(key);

}

console.log(mapKeys);

Output – [“1”, “2”, “3”]

In the above code, we have created a map with three key-value pairs.

Then we use a for…of loop on the map keys to get an array of the map keys and store it in the mapKeys variable. Finally, we print out this array using console.log().

This is how you can convert map keys to an array in JavaScript.

I hope this article was helpful. Thank you for reading! 🙂

Leave a Reply