A map is a data structure used to store key-value entries. We can easily invoke the forEach()
method to iterate over the key-value pair of the map.
map.forEach((key, value) =>{// iterate over key/value pairs})
key
and value
: These are the key-value pairs of the map we want to iterate over.This method returns a loop.
Let's look at the code below:
// create some Mapslet evenNumbers = new Map<string, number>([["two", 2], ["four", 4], ["eight", 8]])let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])// invoke the forEach() methodevenNumbers.forEach((key, value)=>{// log out each entryconsole.log(key, value)})countries.forEach((key, value)=>{// log out each entryconsole.log(key, value)})
forEach()
method to loop through the maps and print each entry of the maps to the console.