![]() |
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() methodThe forEach() method is used on Map in TypeScript to iterate through the key-value pairs and executes the callback function for each element with the arguments as the value, key. This order of iteration is based on the insertion order of the elements. Syntax:map.forEach((value: V, key: K, map: Map<K, V>) => { Example: The below code uses the forEach() method to iterate over Map elements in TypeScript.
Output: Key: DSA, Value: Data Structures and Algorithms Using for…of LoopThe for…of loop in TypeScript iterates through the key-value pairs of the Map, and automatically deconstructs each entry into the key and value components. Syntax:for (let [key, value] of map) { Example: The below example uses for…of Loop to iterate over Map elements in TypeScript.
Output: Key: DSA, Value: Data Structures and Algorithms Using entries() methodThe entries() method in TypeScript iterates over the key-value pairs which returns the iterator object that creates the key, and value array of each element in the Map. This returned iterator is then used in the for…of loop to iterate over the Map entries. Syntax:let iterator: IterableIterator<[K, V]> = map.entries(); Example: The below uses the entries() method to iterate over Map elements in TypeScript.
Output: Key: DSA, Value: Data Structures and Algorithms Using Array.from() with map.entries()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]) => { Example: Below is the implementation of the above-discussed approach.
Output: Key: DSA, Value: Data Structures and Algorithms Using Map.keys() and Map.get() MethodsAnother approach to iterate over the Map elements in TypeScript is by using the Map.keys() method in combination with the Map.get() method. This method first retrieves all the keys of the Map using Map.keys(), and then iterates over these keys to access the corresponding values using Map.get(). This approach provides a straightforward way to access both keys and values of the Map. Example: The below example demonstrates how to use Map.keys() and Map.get() methods to iterate over Map elements in TypeScript.
Output: Key: DSA, Value: Data Structures and Algorithms |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |