Languages
[Edit]
EN

TypeScript - iterate over Map

0 points
Created by:
Paluskitten
356

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join