A map holds data in the form of key value pairs where each key is associated to a value.
Keys should be unique while values may be duplicate.
Map is a data structure introduced in ES6.

In this article, we will take a look at typescript map in detail covering topics such as

Create map

A typescript map is created using constructor of Map interface and new operator as shown in below syntax

let map = new Map();

This will create an empty map with no key-value pairs present.

There is another way of creating a map with initial or default values using another Map constructor by passing an array where each array element is an array of two elements.
First element of each element becomes the key and second becomes the value as shown below

let m = new Map([
      ['English', 'EN'],
      ['French', 'FR'],
      ['German', 'GE'],
    ]);

Each key-value pair is called an entry.

Add entries to map

To add key-value pairs to a map, use its set() method. set() takes two arguments, first is the key and second is the value.

let m = new Map();
m.set("English", "EN")

Data type of key and value of an entry can be different.

It is not necessary that data type of all the keys is same. That is, one key may be a string, while other may be a number. Same is the case with values.
Though this is allowed but not a best practice.

Get value from map

To retrieve value associated to a particular key in map, get() method is used.
get() accepts a key as argument and returns the value by key. Example,

le m = new Map();
m.set("English", "EN");
m.get("English");

If the key in get() does not exist in the map, then it will return undefined.

Update value

When set() is called with an existing key, it updates or overwrites the value associated to that key. So, if set() is called multiple times with the same key, then the value given in last set() remains. Example,

let m = new Map();
m.set("A", 1);
m.set("A", 2);
m.set("A", 3);
m.get("A"); // will return 3

Delete value from map

To remove a value from map, use its delete() method. delete() accepts a key and removes the entry or key-value pair from the map. Example,

let m = new Map(); 
// add values 
m.set("A", 1);
m.set("B", 1);
m.set("C", 1);
// delete entry
m.delete("B");
m.get("B"); // will be undefined

Map size

A map has a size property which returns the number of key-value pairs in the map. It is also called the length of map. Example,

let m = new Map();
m.set("A", 1); 
m.set("B", 1); 
m.set("C", 1);
console.log(m.size); // will be 3

Iterate map

There are different methods to loop over a map and they are explained below.

1. Using for-of loop

Syntax of for-of method is

for(let <variableName> of map) {
  // code
}

where variableName contains an entry of the map in each iteration.

Each entry will be an array
of two elements where first element of array is the key and second is the value. Example,

let m = new Map(); 
m.set("A", 1); 
m.set("B", 2);
for(let e of m) {
  console.log('Map entry:', e);
  console.log('Key:' + e[0] + ', Value: '+e[1]);
}

Output on browser console will be

Map entry: (2) [“A”, 1]
Key: A, Value: 1
Map entry: (2) [“B”, 2]
Key: B, Value: 2

 

Key and value of each entry can directly assigned to different variables using javascript array destructuring syntax as shown below

let m = new Map(); 
m.set("A", 1); 
m.set("B", 2); 
for(let [k, v] of m) { 
  console.log('Key:' + k + ', Value: ' + v); 
}

Notice the loop variable.

2. Using map.keys()

keys() method returns an iterator object which contains all the keys of the map. This iterator can be iterated using a for-of loop as shown below.

let m = new Map(); 
m.set("A", 1); 
m.set("B", 2); 
for(let k of m.keys()) { 
  console.log('Key:' + k + ', Value: ' + m.get(k)); 
}

The loop variable will contain key of each map entry.
To retrieve the value, use get() method of map.

3. Iterating over map values

If you are interested in getting the values of the map, use values() method. values() returns an iterator that contains all the values of the map, which can be iterated using for-of. Example,

let m = new Map(); 
m.set("A", 1); 
m.set("B", 2); 
for(let v of m.values()) { 
  console.log('Value: ' + v); 
}

4. Using map.entries()

entries() method returns an iterator whose each element is a map entry or an array of two elements. First element of this array is the key and second is the value. Example,

let m = new Map(); 
m.set("A", 1); 
m.set("B", 2); 
for(let [k,v] of m.entries()) { 
  console.log('Key:' + k + ', Value: ' + v); 
}

This method is similar to the first method.

5. Using forEach()

Typescript map forEach() method accepts a callback function as argument. This function accepts 2 arguments: first is the value and second is the key.
This callback function is invoked for every map entry once. Example,

let m = new Map();
m.set("A", 1);
m.set("B",2);
m.forEach((k,v) => {
  console.log(k,v);
});

Note that in the above example, forEach() accepts an arrow function.

Remember that all these methods retrieve keys, values or entries in the same order in which they were inserted.

Map to array

As we have seen, each entry of the map is an array of two elements.
So, it is possible to convert a map to an array of arrays as shown below.

let m = new Map();
m.set("A", 1);
m.set("B", 2);
m.set("C", 3);
let arr = Array.from(m);
console.log(arr);

from() method of Array object accepts an iterable as argument and converts it to an array. A map is an iterable, so it can be passed to from().
Output of above code is

0: [“A”, 1]
1: [“B”, 2]
2: [“C”, 3]

In this article, we learnt about Typescript map in detail and how we can use it in detail.
Hope the article was useful.