How to use Array.from() with map.entries() In Typescript
The combination of Array.from() with map.entries() provides a convenient way to iterate over the key-value pairs of a Map in TypeScript. This approach converts the Map’s entries into an array of key-value pairs, which can then be iterated over using array iteration methods.
Syntax:
Array.from(map.entries()).forEach(([key, value]: [K, V]) => {
// code
});
Example: Below is the implementation of the above-discussed approach.
let geeksMap = new Map<string, string>();
geeksMap.set("DSA", "Data Structures and Algorithms");
geeksMap.set("CP", "Competitive Programming");
geeksMap.set("AI", "Artificial Intelligence");
Array.from(geeksMap.entries()).forEach(([key, value]: [string, string]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
Output:
Key: DSA, Value: Data Structures and Algorithms
Key: CP, Value: Competitive Programming
Key: AI, Value: Artificial Intelligence
How to Iterate over Map Elements in TypeScript ?
In TypeScript, iterating over the Map elements means accessing and traversing over the key-value pairs of the Map Data Structure. The Map is nothing but the iterative interface in TypeScript. We can iterate over the Map elements in TypeScript using various approaches that include inbuilt methods and simple looping.
Table of Content
- Using forEach() method
- Using for…of Loop
- Using entries() method
- Using Array.from() with map.entries()
Contact Us