EN
TypeScript - iterate over Map
0
points
In this article, we would like to show you how to iterate over Map in TypeScript.
Quick solution:
myMap.forEach((value: number, key: string) => {
console.log(key, value);
});
or:
for (const [key, value] of myMap) {
console.log(key, value);
}
or:
for (const entry of Array.from(myMap.entries())) {
const key = entry[0];
const value = entry[1];
console.log(key, value);
}
Practical examples
1. Using forEach
const myMap = new Map<string, number>([
['A', 65],
['B', 66],
['C', 67],
]);
myMap.forEach((value: number, key: string) => {
console.log(key, value);
});
Output:
A 65
B 66
C 67
2. Using for
loop
const myMap = new Map<string, number>([
['A', 65],
['B', 66],
['C', 67],
]);
for (const [key, value] of myMap) {
console.log(key, value);
}
Output:
A 65
B 66
C 67
3. Using Array.from()
with Map.entries()
method
const myMap = new Map<string, number>([
['A', 65],
['B', 66],
['C', 67],
]);
for (const entry of Array.from(myMap.entries())) {
const key: string = entry[0];
const value: number = entry[1];
console.log(key, value);
}
Output:
A 65
B 66
C 67