Demystifying TypeScript Map Iteration: A Guide to `forEach()`, `for...of`, and More
- In TypeScript, a
Map
is a collection of key-value pairs, similar to dictionaries in other languages. - Unlike objects, keys in a
Map
can be of any data type, not just strings. This provides more flexibility.
Iterators
- An iterator is an object that allows you to access elements in a collection one at a time.
- It provides a
next()
method that returns the next element in the iteration, along with adone
property indicating whether there are more elements.
Iterating over a TypeScript Map
There are three common ways to iterate over a TypeScript Map
:
-
Using the
forEach()
method:- This is a built-in method that takes a callback function as an argument.
- The callback function is executed for each key-value pair in the
Map
. - The callback function typically receives three arguments:
- The value of the current key-value pair.
- The key itself.
- The entire
Map
object (optional).
const myMap = new Map([ ['name', 'Alice'], [1, 'One'], ]); myArray.forEach((value, key) => { console.log(key, value); // Output: name Alice, 1 One });
-
Using the
for...of
loop with theentries()
method:- The
entries()
method of aMap
returns an iterator that yields key-value pairs as separate values. - The
for...of
loop can then be used to iterate over these pairs.
for (const [key, value] of myMap.entries()) { console.log(key, value); // Output: same as above }
Destructuring in
for...of
loop:- You can use destructuring within the loop to directly access the key and value.
for (const [key, value] of myMap) { console.log(key, value); // Output: same as above }
- The
-
Using the
keys()
orvalues()
methods with afor...of
loop:- The
keys()
method returns an iterator for the keys in theMap
. - You can use these iterators with a
for...of
loop to iterate over the keys or values individually.
// Iterating over keys for (const key of myMap.keys()) { console.log(key); // Output: name, 1 } // Iterating over values for (const value of myMap.values()) { console.log(value); // Output: Alice, One }
- The
const myMap = new Map([
['name', 'Alice'],
[1, 'One'],
]);
myArray.forEach((value, key) => {
console.log(key, value); // Output: name Alice, 1 One
});
Explanation:
- We create a
Map
namedmyArray
with two key-value pairs. - The
forEach()
method is called onmyArray
. - It takes a callback function as an argument that receives three arguments:
myArray
(optional): The entireMap
object.
- Inside the callback function, we can access the key and value using
key
andvalue
arguments, respectively. - We log both the key and value to the console.
for (const [key, value] of myMap.entries()) {
console.log(key, value); // Output: name Alice, 1 One
}
- The
for...of
loop iterates over this iterator. - Inside the loop, each iteration receives an array with two elements:
- The first element is the key.
- The second element is the value.
- We use destructuring to directly access the key and value using
[key, value]
syntax.
// Iterating over keys
for (const key of myMap.keys()) {
console.log(key); // Output: name, 1
}
// Iterating over values
for (const value of myMap.values()) {
console.log(value); // Output: Alice, One
}
- Inside each loop, the iteration variable receives the corresponding key or value directly.
This approach involves converting the Map
to an array using Array.from()
and then using the map()
method (which works on arrays) to process the elements. However, it's generally less efficient for iteration and might be less readable than the other methods. It's suitable when you need to perform specific array-like operations on the Map
data.
const myMap = new Map([
['name', 'Alice'],
[1, 'One'],
]);
const processedData = Array.from(myArray).map(([key, value]) => {
// Process key and value here
return someNewValue;
});
console.log(processedData); // This will contain an array of processed values
Using a spread operator with destructuring (modern syntax, not for all browsers):
This method utilizes the spread operator (...
) with destructuring to iterate over the Map
entries directly within another operation. It's a concise approach but might not be compatible with older browsers that don't support these features.
const myMap = new Map([
['name', 'Alice'],
[1, 'One'],
]);
const [name, value1, ...otherEntries] = [...myArray.entries()]; // Destructure entries
console.log(name, value1); // Output: name Alice
console.log(otherEntries); // Remaining entries as an array
Choosing the right method:
- For most common iteration scenarios,
forEach()
,for...of
withentries()
,keys()
, orvalues()
are the recommended approaches. - Use
Array.from()
andmap()
if you specifically need to perform array-like operations on theMap
data. - The spread operator method is a modern, concise approach but consider browser compatibility before using it.
typescript dictionary iterator