TypeScript Map

TypeScript map is a new data structure added in ES6 version of JavaScript. It allows us to store data in a key-value pair and remembers the original insertion order of the keys similar to other programming languages. In TypeScript map, we can use any value either as a key or as a value.

Create Map

We can create a map as below.

snippet
var map = new Map();

Map methods

The TypeScript map methods are listed below.

SN Methods Descriptions
1. map.set(key, value) It is used to add entries in the map.
2. map.get(key) It is used to retrieve entries from the map. It returns undefined if the key does not exist in the map.
3. map.has(key) It returns true if the key is present in the map. Otherwise, it returns false.
4. map.delete(key) It is used to remove the entries by the key.
5. map.size() It is used to returns the size of the map.
6. map.clear() It removes everything from the map.

Example

We can understand the map methods from the following example.

snippet
let map = new Map();

map.set('1', 'abhishek');   
map.set(1, 'www.javatpoint.com');     
map.set(true, 'bool1'); 
map.set('2', 'ajay');

console.log( "Value1= " +map.get(1)   ); 
console.log("Value2= " + map.get('1') ); 
console.log( "Key is Present= " +map.has(3) ); 
console.log( "Size= " +map.size ); 
console.log( "Delete value= " +map.delete(1) ); 
console.log( "New Size= " +map.size );

Output:

When we execute the above code snippet, it returns the following output.

TypeScript map

Iterating Map Data

We can iterate over map keys or values or entries by using 'for...of' loop. The following example helps to understand it more clearly.

Example

snippet
let ageMapping = new Map();
 
ageMapping.set("Rakesh", 40);
ageMapping.set("Abhishek", 25);
ageMapping.set("Amit", 30);
 
//Iterate over map keys
for (let key of ageMapping.keys()) {
    console.log("Map Keys= " +key);        
}
//Iterate over map values
for (let value of ageMapping.values()) {
    console.log("Map Values= " +value);    
}
console.log("The Map Enteries are: "); 
//Iterate over map entries
for (let entry of ageMapping.entries()) {
    console.log(entry[0], entry[1]); 
}

Output:

TypeScript map
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents