This post will discuss how to extract keys and values from a Map in JavaScript.

There are several methods to get an array of map keys and values in JavaScript. A map is an object that holds key-value pairs and remembers the original insertion order of the keys. Here are some of the methods that we can use to extract keys and values from a Map:

1. Using Array.from() function

We can use the Array.from() function to convert the iterator objects returned by Map.keys() and Map.values() into arrays. The keys() function returns a new iterator object that contains the keys of the map, while the values() function returns a new iterator object that contains the values of the map. Here’s an example:

Download  Run Code

 
If we want to get an array of both keys and values, we can use the Map.entries() function, which returns an iterator of the map’s key-value pairs as arrays. Then, we can use the Array.from() function to convert the iterator object to an array. Here’s an example:

Download  Run Code

2. Using spread syntax

We can also use the spread syntax (…) to convert the iterator objects to arrays. The idea is to obtain the arrays of map keys and values using the keys() and values() methods, and then convert them to arrays using the spread operator. Here’s an example:

Download  Run Code

 
To get an array of key-value pairs, we can use the spread syntax to convert the iterator object returned by the Map.entries() function to an array. Here’s an example:

Download  Run Code

3. Using Map.entries() function

The Map.entries() function returns a new iterator object that contains an array of [key, value] pairs for each element in the map. We can use this function to get both the keys and values of the map as a single iterable, and convert it to an array using the Array.from() function or the spread operator (…). Then, we use array destructuring to separate the keys and values into two arrays. For example:

Download  Run Code

4. Using for…of loop

The for…of loop can be used to iterate over any iterable object, such as a map. The loop can access both the key and value of each element in the map and store them in separate arrays. For example:

Download  Run Code

That’s all about extracting keys and values from a Map in JavaScript.