TypeScript Map Collections Tutorial
In this TypeScript tutorial we learn about the map collection which can store multiple values with custom keys.
We learn how to instantiate new map objects, how to add values, get values one by one or in a loop, how to delete single values or clear the whole map without destroying the object.
We also learn how to check if a map contains a value before we access or delete it, and lastly, we discuss one way to pass a map to a function.
- What is a map
- Compile for Javascript ES6+
- How to create (instantiate) a map
- How to add values to a map
- How to get values from a map
- How to get values from a map in a for..of loop
- How to delete single values from a map
- How to check if a map contains a value
- How to use a map as a function argument
- How to clear all values from a map
- Summary: Points to remember
What is a map
A map is a data structure introduced in Javascript ES6, and is supported by TypeScript.
A map is a collection of key/value pairs, similar to an array or tuple. Instead of a numerical index, we define custom keys (like words) that correspond to our values.
key | "emp1" | "emp2" | "emp3" | "emp4" |
value | "John" | "Jane" | "Jack" | "Jill" |
Compile for Javascript ES6+
By default, TypeScript will not compile for Javascript ES6. Because maps are part of ES6 we need to tell the compiler to use ES6 libraries, like the map.
To do this, we add the --target es6 flag to our compile command.
tsc filename.ts --target es6
Note that the flag is prefixed with two dashes.
tsc main.ts --target es6
Once the script is compiled, we can run the .js file normally.
// compile es6 .ts file
tsc main.ts --target es6
// run compiled .js file
node main.js
How to create (instantiate) a map
To define a map, we have to create a new instance object of it. Instance objects are always created with the new keyword.
// instantiate map
let map_name = new Map()
Note that we don’t specify a type when instantiating the map object.
let country = new Map()
How to add values to a map
As an object, we have to use special functions to add values to a map.
A map uses the .set() method to add a single value. The first argument is the key , and the second argument is the value .
// set key/value
name.set( key, value )
Both the keys and values may be of any type we want.
let country = new Map()
country.set("AU", "Australia")
country.set("DE", "Germany")
country.set("US", "United States")
country.set("UK", "United Kingdom")
country.set("ZA", "South Africa")
How to get values from a map
Because a map is an object, we cannot access values with square brackets, like we do with an array.
We need to use the .get() method to retrieve values from the map or set.
name.get( key )
let country = new Map()
country.set("AU", "Australia")
country.set("DE", "Germany")
country.set("US", "United States")
country.set("UK", "United Kingdom")
country.set("ZA", "South Africa")
// store value
let a:string = country.get( "AU" )
// access value directly
console.log( country.get("AU") )
In the example above, we get the value located at the key ‘AU’ twice.
First, we store it in a variable of type string. The type of the variable is for the value, not the key. Then, we also log it to the console by passing the .get() method directly as a parameter.
How to get values from a map in a for..of loop
The easiest method to loop through a collection object is with the for..of loop.
The for..of loop will iterate for every value of the map.
for(let temp_value of list_name) {
// use temp_value
}
The ‘temp_value’ variable is the value of the element in the current iteration the loop is in while running.
let country = new Map()
country.set("AU", "Australia")
country.set("DE", "Germany");
country.set("US", "United States")
country.set("UK", "United Kingdom")
country.set("ZA", "South Africa")
// loop for..of
for(let item of country) {
console.log(item)
}
The for..of loop will automatically get the amount of values in the map and stop looping when it reaches the end.
How to delete single values from a map
To delete single values from a map, we use the .delete() method and specify the key as the argument.
// instantiate
let name = new Map()
// delete element at key
name.delete( key )
let country = new Map()
country.set("AU", "Australia")
country.set("DE", "Germany")
country.set("US", "United States")
country.set("UK", "United Kingdom")
country.set("ZA", "South Africa")
// delete entry "AU"
country.delete("AU")
// confirm deletion
for(let item of country) {
console.log(item)
}
When we run the script, we can see in the output that the ‘Australia’ entry was deleted.
How to check if a map contains a value
To help us avoid possible runtime errors, we can check if a map contains a value before we try to access or delete it.
For this we use the .has() method.
// instantiate
let name = new Map()
// set key/value
name.set( key, value )
// existance check
name.has( key )
If the value exists, the method returns true. Otherwise, it will return false.
let country = new Map()
country.set("AU", "Australia")
// check if value exists
console.log( country.has("AU") )
In the example above, the value does exist in the map so it returns true.
How to use a map as a function argument
A quick way to use a map as a function argument, is by specifying its type as any .
let country = new Map()
country.set("AU", "Australia")
country.set("NZ", "New Zealand")
// delete entry with key "AU"
console.log( delEntry(country, "AU") )
// confirm deletion
for(let i of country) {
console.log(i)
}
// function to safely delete
// an entry from a map
function delEntry(map: any, key: any): boolean {
// check if the key exists
// before deleting it
if(map.has(key)) {
map.delete(key)
}
return true
}
The map parameter will represent the map collection we want to access, and the key parameter will represent the key in the map.
Inside the function body we use the map parameter to access the .has() and .delete() methods available to a map.
note Remember that the any type skips type checking, which is why we use TypeScript in the first place.
How to clear all values from a map
We can wipe all the values from a map without destroying the map itself.
To do this we use the .clear() method.
// instantiate
let name = new Map()
// set key/value
name.set( key, value )
// existance check
name.clear()
let country = new Map()
country.set("AU", "Australia")
country.set("NZ", "New Zealand")
// clear the array of all values
console.log( country.clear() )
When a map is cleared, it will show as ‘undefined’.
Summary: Points to remember
- A map is a collection of key/value pairs similar to an array, but with custom keys instead of a numerical index.
- Maps are part of the ES6+ specification and needs the added compiler flag --target es6 or greater.
- Map objects need to be instantiated with the new keyword.
- To add a single value to a map, we use the .set() method.
- To retrieve a value from a map, we use the .get() method.
- To access values in a loop, we use the for..of loop.
- To delete single values from a map, we use the .delete() method.
- To check if a map has a value inside it, we use the .has() method.
- To clear all the values from a map without destroying the object, we use the .clear() method.