This typescript tutorial explains TypeScript Map, how we can create a map in typescript, various map properties and methods. We will also discuss how to iterate over Map entries, Array map, clone and merge maps, merge map with an array, Convert Map Keys/Values to an Array, Weak Map, etc.
If you are new to typescript, then check out my previous tutorial on TypeScript tutorial (Step by Step). You can download latest version of typescript (TypeScript 3.4).
TypeScript Map
Maps are an important new feature of ECMAScript 6 (ES6) and can be used in a wide variety of use cases for storing key/value pairs. Map is a new data structure which lets you map keys to values without the drawbacks of using Objects.
Create Map in TypeScript
We can easily create Map in typescript using a new keyword like below:
var map = new Map();
Or we can also create a map in typescript like below:
let productMap = new Map();
We could initialize the typescript Map with a an array of key-value pairs:
var map = new Map([
[ "apple", 10 ],
[ "banana", 20 ],
[ "carraot", 30 ]
]);
TypeScript Map Properties and Methods
We can then add entries to typescript map by using the set method:
var map = new Map();
map.set("apple",10);
map.set("banana",20);
map.set("carrot",30);
We can extract a value from typescript map by using the get method:
map.get("apple"); //10
We can check to see if a key is present using the has method:
map.has("apple");//true
We can delete entries from typescript map using the delete method:
map.delete("apple");//true
We can check number of entries in Map using the size property in typescript.
map.size
We can empty an entire Map by using the clear method in typescript map.
map.clear()// Clears the map of all entries
Iterate over Map entries in TypeScript
We use the for-of looping operator to loop over entries in a Map in typescript.
Using keys()
The keys method returns the keys in the map as an array which we can loop over using for-of like so.
Example:
var map = new Map();
map.set("a",10);
map.set("b",20);
map.set("c",30);
for (let key of map.keys()) {
console.log(key);
}
//output:
a
b
c
Using values():
The values() method returns the keys in the map as an array which we can loop over using for-of like so.
Example:
var map = new Map([
[ "a", 10 ],
[ "b", 20 ],
[ "c", 30 ]
]);
for (let value of map.values()) {
console.log(value);
}
//output:
10
20
30
Using entries():
The entries() method returns the [key, value] pairs in the map as an array which we can loop over using for-of like so.
Example:
var map = new Map([
[ "a", 10 ],
[ "b", 20 ],
[ "c", 30 ]
]);
for (let entry of map.entries()) {
console.log(entry[0], entry[1]);
}
//output:
a 10
b 20
c 30
Using destructing we can access the keys and values directly.
var map = new Map([
[ "a", 10 ],
[ "b", 20 ],
[ "c", 30 ]
]);
for (let [key, value] of map.entries()) {
console.log(key, value);
}
//output:
a 10
b 20
c 30
we can call keys and values on a map instance with out call entries().
Example:
var map = new Map([
[ "a", 10 ],
[ "b", 20 ],
[ "c", 30 ]
]);
for (let [key, value] of map) {
console.log(key, value);
}
//output:
a 10
b 20
c 30
forEach():
Provides a convenient way to iterate the map. You can get keys, values itself very easily.
Example:
let map = new Map([
['a', 1],
['b', 2],
]);
map.forEach((value, key) => {
console.log(key, value);
});
//output:
a 1
b 2
2d Arrays to Maps:
Maps can take 2d arrays in the constructor. Each array entry should have the format [key, value].
Example:
var arr = [['a', 1], ['b', 2]]
var m = new Map(arr)
Spreading iterables
The spread operator (…) turns iterable into the arguments of a function or parameter call. Spread also turns iterable into the elements of an array. That lets us convert the result of Map.prototype.keys() (an iterable) into an array:
Example:
let map = new Map([
[1, 'a'],
[2, 'b'],
[3, 'c'],
]);
let arr = [...map.keys()];
console.log(arr)
//output:
[1,2,3]
TypeScript Mapping and filtering
We can map() and filter() arrays, but there are no such operations for typescript maps. for that solution:
- Convert the map into an array of [key, value] pairs.
- Map or filter the array.
- Convert the result back to a map.
let map = new Map()
.set(1, 'a')
.set(2, 'b')
.set(3, 'c');
.set(4, 'd');
let map1 = new Map(
[...map]
.filter(([k, v]) => k < 4)
);
console.log(map1)
//output:
{1 => 'a', 2 => 'b', 3 => 'c'}
Array map() in TypeScript
map() method creates a new array with the results of calling a provided function on every element in this array.
Syntax:
array.map(callback[, thisObject]);
Example:
let num = [4,9,25];
let sqrRoots = num.map(Math.sqrt);
console.log("roots is : " + sqrRoots );
//output:
roots is : 2,3,5
Cloning and merging Maps in TypeScript
Cloning: Just like an Arrays, TypeScript Maps can be cloned:
Example:
var map = new Map([
[1, 'a'],
[2, 'b']
]);
console.log(map)
var clone = new Map(map);
console.log(clone)
console.log(clone.get(1));
console.log(map === clone);
//output:
Map { 1 => 'a', 2 => 'b' }
Map { 1 => 'a', 2 => 'b' }
a
false
Keep in mind that the data itself is not cloned
Merging: TypeScript Maps can be merged, maintaining key uniqueness:
Example:
var map1 = new Map([
[1, 'a'],
[2, 'b'],
[3, 'c'],
]);
var map2 = new Map([
[4, 'd'],
[5, 'e']
]);
var merged = new Map([...map1, ...map2]);
console.log(merged);
console.log(merged.get(1));
console.log(merged.get(2));
console.log(merged.get(4));
console.log(merged.keys());
console.log(merged.values());
//output:
Map { 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e' }
a
b
d
MapIterator { 1, 2, 3, 4, 5 }
MapIterator { 'a', 'b', 'c', 'd', 'e' }
TypeScript Map merge with an Array
TypeScript Maps can be merged with Arrays.
Example:
var map1 = new Map([
[1, 'a'],
[2, 'b'],
[3, 'c'],
]);
var map2 = new Map([
[4, 'd'],
[5, 'e']
]);
var merged = new Map([...map1, ...map2,[6, 'f']]);
console.log(merged);
console.log(merged.size);
console.log(merged.get(1));
console.log(merged.get(4));
console.log(merged.get(6));
console.log(merged.keys());
console.log(merged.values());
//output:
Map { 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e', 6 => 'f' }
6
a
d
f
MapIterator { 1, 2, 3, 4, 5, 6 }
MapIterator { 'a', 'b', 'c', 'd', 'e', 'f' }
Relation with Array objects in TypeScript
We can Initialize a new Map from the contents of an Array in typescript.
Example:
var kvArray=[{key: 1, value:'value1'}, {key:2, value:'value2'}];
var map = new Map(kvArray.map(x => [x.key, x.value] as [number, string]));
console.log(Array.from(map));
console.log(map.get(1));
console.log(Array.from(map.keys()));
console.log(Array.from(map.values()));
console.log([...map]);
//output:
[ [ 1, 'value1' ], [ 2, 'value2' ] ]
value1
[ 1, 2 ]
[ 'value1', 'value2' ]
[ [ 1, 'value1' ], [ 2, 'value2' ] ]
Convert Map Keys/Values to an Array in TypeScript
Map.keys() returns a MapIterator object which can be converted to Array using “Array.from” in typescript.
Example: convert Map keys to an array
var map = new Map([
[1, 'a'],
[2, 'b'],
[3, 'c']
]);
let keys = Array.from( map.keys() );
console.log(keys)
let keys1 =[ ...map.keys() ];//spread arrays
console.log(keys1)
//output:
[ 1, 2, 3 ] // Array.from()
[ 1, 2, 3 ] //...map.keys()
Example: convert Map values to an array
var map = new Map([
[1, 'a'],
[2, 'b'],
[3, 'c']
]);
let values = Array.from( map.values() );
console.log(values)
let keys =[ ...map.keys() ];
console.log(keys)
//output:
[ 'a', 'b', 'c' ]// map.values
[ 1, 2, 3 ] //map.keys
No duplicate elements in the map:
A map can have a key value which can be a string, number, object or even NaN. The map doesn’t contain duplicate keys.
Example:
var map = new Map([
[1, 'a'],
[1, 'b'],
[2, 'c']
]);
console.log(map);
//output:
[ [ 1, 'b' ], [ 2, 'c' ] ]// It removed duplicate [1, 'a']
Weak Map in TypeScript
- The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.
- Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can’t be a WeakMap key).
- The key in a WeakMap is held weakly. What this means is that, if there are no other strong references to the key, then the entire entry will be removed from the WeakMap by the garbage collector.
- Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys).
Creating weakmap using a new keyword:
var weakmap = new WeakMap()
functions in Weak Map:
- set(key: K, value?: V): Sets the value for the key in the WeakMap object. Returns the WeakMap object.
- get(key: K): Returns the value associated with the key, or undefined if there is none.
- delete(key: K): Removes any value associated with the key.
- clear(): Removes all key-value pairs associated with a weak map object.
- has(Key: K): Returns a boolean asserting whether a value has been associated with the key in the Map object or not.
Example:
var wm1 = new WeakMap(),
wm2 = new WeakMap(),
wm3 = new WeakMap();
var v1 = {},
v2 = function(){},
v3 = window;
wm1.set(v1, 37);
wm1.set(v2, "azerty");
wm1.get(v2); // "azerty"
wm1.has(v2); // true
wm2.has(v2); // false
wm2.has(v3); // true (even if the value itself is 'undefined')
wm3.set(v1, 37);
wm3.get(v1); // 37
wm1.has(v1); // true
wm1.delete(v1);
wm1.has(v1); // false
You may like following TypeScript Tutorials:
- TypeScript Enum (With Examples)
- TypeScript Dictionary (With Examples)
- TypeScript Date (With Examples)
- TypeScript Set and Weakset (with Examples)
In this article, we learned about basic concepts of typescript Map, how we can create a map in typescript, various map properties, and methods, how to iterate over Map entries, Array map, clone and merge maps, merge map with an array, Convert Map Keys/Values to an Array, Weak Map, etc.
I am Bijay a Microsoft MVP (8 times –Â My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com
It’s a good article
It puzzles me that one of the primary purposes of Typescript over Java Script is the use of types. Yet, most blogs explaining typescript continue to not use Types, all their examples, as yours are, just use Type any.
I believe your article would be must better if you defined your Map using Types
const map = new Map() and avoided the implicitly use of ‘any’ or ‘object’ in your examples
I tried to post with the use of maps using generics types new Map (open angle bracket) string, (close angle bracket), (open angle bracket) number(close angle bracket(). But your text filter simply removed the all open and close brackets. What is the point of a blog on typescript if you can’t respond with examples that use Types !!!!