TypeScript Map is a new data structure introduced in ES6. A Map allows us store key-value pairs similar to the Maps in other programming languages e.g. Java or C#.
1. Create TypeScript Map
Use Map
type and new
keyword to create a Map
in TypeScript.
let myMap = new Map();
To create a Map with initial values, pass the values as an array to the Map
constructor.
let myMap = new Map([ ["key1", "value1"], ["key2", "value2"] ]);
2. Add, retrieve, delete entries from Map
The common operations abailable over a Map
are:
map.set()
– method to add entries inMap
.map.get()
– to retrieve an entry fromMap
.map.has()
– to existence of an entry in theMap
.map.delete()
– deletes an entry from theMap
.map.size
– ‘size’ property will return size ofMap
.
let nameAgeMapping = new Map(); //Set entries nameAgeMapping.set("Lokesh", 37); nameAgeMapping.set("Raj", 35); nameAgeMapping.set("John", 40); //Get entries nameAgeMapping.get("John"); //40 //Check entry is present or not nameAgeMapping.has("Lokesh"); //true nameAgeMapping.has("Brian"); //false //Size of Map with nameAgeMapping.size; //3 //Delete an entry nameAgeMapping.delete("Lokesh"); // true //Clear whole Map nameAgeMapping.clear(); //Clear all entries
3. Iterating over Map Entries
A Map
object iterates its elements in insertion order. A for each loop returns an array of [key, value]
for each iteration.
Use 'for...of' loop
to iterate over map keys, values or entries.
let nameAgeMapping = new Map(); nameAgeMapping.set("Lokesh", 37); nameAgeMapping.set("Raj", 35); nameAgeMapping.set("John", 40); //Iterate over map keys for (let key of nameAgeMapping.keys()) { console.log(key); //Lokesh Raj John } //Iterate over map values for (let value of nameAgeMapping.values()) { console.log(value); //37 35 40 } //Iterate over map entries for (let entry of nameAgeMapping.entries()) { console.log(entry[0], entry[1]); //"Lokesh" 37 "Raj" 35 "John" 40 } //Using object destructuring for (let [key, value] of nameAgeMapping) { console.log(key, value); //"Lokesh" 37 "Raj" 35 "John" 40 }
Drop me your questions in the comments section.
Happy Learning !!
Kola Rajesh
What is the purpose of using the Map() iterator in javascript?
awewae
how to update map key
Lokesh Gupta
Keys are not supposed to be updated in maps.
Ankita Garg
I have a map that consists of key, value pairs where value is in the form of an array of objects i.e. basically of the form
myMap
a, 123
b , 45
c, 6789
I tried printing it on the console with the help of nested for loops but it just won’t run.
Could you help me out ??
Raju
How to import this Map in typescript file???
Wolfos
You don’t need to import anything. It’s part of the language.