What is the values() method of a Map in TypeScript?
Overview
We can use a Map to store the data with key-value pairs as well as dictionary data. Using the values() method, we get all the values of every key present in the dictionary. It returns these values as an iterator.
Syntax
Map.values()
The values() method of a Map in TypeScript
Parameters
Map: This is the map whose values we want to get.
Return value
It returns an iterator of the Map type containing its values.
Example
// Create some mapslet oddNumbers = new Map<string, number>([["one", 1], ["three", 3], ["five", 5]])let products = new Map<string, number>([["rice", 500], ["bag", 10]])let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])let isOld = new Map<string, boolean>([["James", false], ["Jane", true], ["Doe", false]])let nullishMap = new Map<null, null>()// get the iteratorslet itr1 = oddNumbers.values()let itr2 = products.values()let itr3 = countries.values()let itr4 = isOld.values()let itr5 = nullishMap.values()// log out the iteratorsconsole.log(itr1)console.log(itr2)console.log(itr3)console.log(itr4)console.log(itr5)// log out values for any of the iteratorsfor (let value of itr1) {console.log(value);}
Explanation
- Lines 2–6: We create some maps in TypeScript and initialize them with some data.
- Lines 9–13: We use the
values()method to get the iterators of the created sets. - Lines 16–20: We use
console.log()to log theMapiterators to the console. - Lines 23: We use the
for ofloop to iterate over one of the iterators. Next, we print its values to the console screen.