How to Convert Map Keys and Values to an Array in JavaScript
A Map object stores key-value pairs, but often you need to work with just the keys or just the values as a standard array. This is necessary for tasks like filtering, sorting, or passing the data to functions that expect an array. JavaScript provides a simple and direct way to extract both keys and values.
This guide will teach you the modern, standard methods for converting a Map's keys and values into separate arrays using Array.from() and the spread syntax (...).
Getting an Iterator with .keys() and .values()
Before we can create an array, we must first get an iterator from the Map. An iterator is an object that lets you traverse a collection, one item at a time.
myMap.keys(): Returns a new iterator object that contains the keys for each element in theMapin insertion order.myMap.values(): Returns a new iterator object that contains the values for each element in theMapin insertion order.
These iterators are not arrays themselves, but they can be easily converted into them.
The Core Methods: Array.from() and Spread Syntax (...)
Both Array.from() and the spread syntax are designed to turn an iterable object (like the iterators from .keys() and .values()) into a new array.
Array.from(iterator): This is an explicit and highly readable method. It takes an iterable and returns a new array.[...iterator]: The spread syntax is a more concise, modern alternative that "unpacks" the elements from the iterator into a new array literal.
Both methods are excellent choices and achieve the exact same result. The choice between them is often a matter of coding style.
Basic Example: Getting Keys and Values
Let's convert a Map's keys and values into two separate arrays.
For example, we have a Map and need to get its keys and values as distinct arrays.
// Problem: How to get ['name', 'age'] and ['Alice', 30]?
const userMap = new Map();
userMap.set('name', 'Alice');
userMap.set('age', 30);
The solution:
const userMap = new Map();
userMap.set('name', 'Alice');
userMap.set('age', 30);
// --- Using Array.from() (Very Readable) ---
const keysArray1 = Array.from(userMap.keys());
const valuesArray1 = Array.from(userMap.values());
console.log('Keys (from Array.from):', keysArray1); // Output: Keys (from Array.from): [ 'name', 'age' ]
console.log('Values (from Array.from):', valuesArray1); // Output: Values (from Array.from): [ 'Alice', 30 ]
// --- Using Spread Syntax (...) (Very Concise) ---
const keysArray2 = [...userMap.keys()];
const valuesArray2 = [...userMap.values()];
console.log('Keys (from spread):', keysArray2); // Output: Keys (from spread): [ 'name', 'age' ]
console.log('Values (from spread):', valuesArray2); // Output: Values (from spread): [ 'Alice', 30 ]
An Alternative: The for...of Loop
While the one-liner methods are generally preferred, a traditional for...of loop is a perfectly valid and readable way to build the arrays, especially if you need to perform some logic during the iteration.
Solution:
const userMap = new Map();
userMap.set('name', 'Alice');
userMap.set('age', 30);
const keys = [];
const values = [];
// A for...of loop can iterate directly over a Map.
// We use destructuring to get the key and value.
for (const [key, value] of userMap) {
keys.push(key);
values.push(value);
}
console.log('Keys (from for...of):', keys); // Output: ['name', 'age']
console.log('Values (from for...of):', values); // Output: ['Alice', 30]
This imperative approach can be easier to debug for developers who are less familiar with functional programming concepts.
Conclusion
Converting a Map's keys and values to an array is a simple and common operation in modern JavaScript.
- First, get an iterator by calling
myMap.keys()ormyMap.values(). - Then, convert that iterator to an array using either
Array.from(iterator)for readability or the spread syntax ([...iterator]) for conciseness.
These methods are the recommended best practices for their clarity and efficiency, allowing you to easily work with Map data in array-based operations.