TypeScript Map Object

The Map object holds key-value pairs and remembers the original insertion order of the keys.

Any value (object or primitive value) can be used as a key or a value.

Map is a new data structure introduced in ES6. You can refer toES6 Map and Set。


Create Map

TypeScript uses the Map type and the new keyword to create a Map:

let myMap = new Map();

To initialize a Map, you can pass key-value pairs in the form of an array:

let myMap = new Map([
        ["key1", "value1"],
        ["key2", "value2"]
    ]); 

Map-related functions and properties:

  • map.clear()– Removes all key/value pairs from the Map object.
  • map.set()– Sets a key-value pair and returns this Map object.
  • map.get()– Returns the value corresponding to the key, or undefined if it does not exist.
  • map.has()– Returns a boolean value indicating whether the Map contains the value corresponding to the key.
  • map.delete()– Deletes an element from the Map, returns true on success and false on failure.
  • map.size– Returns the number of key/value pairs in the Map object.
  • map.keys()- Returns an Iterator object that contains the keys of each element in the Map object.
  • map.values()– Returns a new Iterator object that contains the values of each element in the Map object.
  • map.entries()– Returns an iterator that contains all key-value pairs in the Map.

Common Functions

set(key: K, value: V): this- Adds or updates a key-value pair in the Map.

map.set('key1', 'value1');

get(key: K): V | undefined- Gets the value based on the key, returns undefined if the key does not exist.

const value = map.get('key1');

has(key: K): boolean - Checks whether the specified key exists in the Map.

const exists = map.has('key1');

delete(key: K): boolean - Deletes the key-value pair for the specified key, returns true if successfully deleted, otherwise returns false.

const removed = map.delete('key1');

clear(): void - Clears all key-value pairs in the Map.

map.clear();

size: number- Returns the number of key-value pairs in the Map.

const size = map.size;

Iteration Methods

keys(): IterableIterator<K> - Returns an iterator containing all keys in the Map.
for (const key of map.keys()) {
  console.log(key);
}

values(): IterableIterator<V>- Returns an iterator containing all values in the Map.

for (const value of map.values()) {
  console.log(value);
}

entries(): IterableIterator<[K, V]>- Returns an iterator containing all key-value pairs in the Map, each element is a [key, value] array.

for (const [key, value] of map.entries()) {
  console.log(key, value);
}

forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void- Executes the provided callback function once for each key-value pair in the Map.

map.forEach((value, key) => {
  console.log(key, value);
});

Example

Example

const map = new Map<string, number>();

map.set('one', 1);
map.set('two', 2);

console.log(map.get('one')); // Output: 1

console.log(map.has('two')); // Output: true

map.delete('one');

console.log(map.size); // Output: 1

map.forEach((value, key) => {
  console.log(key, value); // Output: two 2
});

map.clear();

console.log(map.size); // Output: 0

Example - test.ts file

let nameSiteMapping = new Map(); //Set Map object nameSiteMapping.set("Google", 1); nameSiteMapping.set("Example", 2); nameSiteMapping.set("Taobao", 3); //Get the value corresponding to the key console.log(nameSiteMapping.get("Example")); // 2 //Determine whether the Map contains a value corresponding to the key console.log(nameSiteMapping.has("Taobao")); // true console.log(nameSiteMapping.has("Zhihu")); // false //Return the number of key/value pairs in the Map object console.log(nameSiteMapping.size); // 3 //Delete Example console.log(nameSiteMapping.delete("Example")); // true console.log(nameSiteMapping); //Remove all key/value pairs from the Map object nameSiteMapping.clear(); //Clear Map console.log(nameSiteMapping);

Usees6Compile:

tsc --target es6 test.ts

Compile the above code to get the following JavaScript code:

Example - test.js file

let nameSiteMapping = new Map(); //Set Map object nameSiteMapping.set("Google", 1); nameSiteMapping.set("Example", 2); nameSiteMapping.set("Taobao", 3); //Get the value corresponding to the key console.log(nameSiteMapping.get("Example")); //40 //Determine whether the Map contains a value corresponding to the key console.log(nameSiteMapping.has("Taobao")); //true console.log(nameSiteMapping.has("Zhihu")); //false //Return the number of key/value pairs in the Map object console.log(nameSiteMapping.size); //3 //Delete Example console.log(nameSiteMapping.delete("Example")); // true console.log(nameSiteMapping); //Remove all key/value pairs from the Map object nameSiteMapping.clear(); //Clear Map console.log(nameSiteMapping);

Execute the above JavaScript code, the output result is:

2
true
false
3
true
Map { 'Google' => 1, 'Taobao' => 3 }
Map {}

Iterate over Map

The elements in a Map object are inserted in order. We can iterate over the Map object, and each iteration returns a [key, value] array.

TypeScript usesfor...ofto implement iteration:

Example - test.ts file

let nameSiteMapping = new Map(); nameSiteMapping.set("Google", 1); nameSiteMapping.set("Example", 2); nameSiteMapping.set("Taobao", 3); //Iterate over the keys in the Map for (let key of nameSiteMapping.keys()) { console.log(key); } //Iterate over the values in the Map for (let value of nameSiteMapping.values()) { console.log(value); } //Iterate over the key => value in the Map for (let entry of nameSiteMapping.entries()) { console.log(entry[0], entry[1]); } //Use object destructuring for (let [key, value] of nameSiteMapping) { console.log(key, value); }

Usees6Compile:

tsc --target es6 test.ts

Compile the above code to get the following JavaScript code:

Example

let nameSiteMapping = new Map(); nameSiteMapping.set("Google", 1); nameSiteMapping.set("Example", 2); nameSiteMapping.set("Taobao", 3); //Iterate over the keys in the Map for (let key of nameSiteMapping.keys()) { console.log(key); } //Iterate over the values in the Map for (let value of nameSiteMapping.values()) { console.log(value); } //Iterate over the key => value in the Map for (let entry of nameSiteMapping.entries()) { console.log(entry[0], entry[1]); } //Use object destructuring for (let [key, value] of nameSiteMapping) { console.log(key, value); }

Execute the above JavaScript code, the output result is:

Google
Example
Taobao
1
2
3
Google 1
Example 2
Taobao 3
Google 1
Example 2
Taobao 3
Other Extensions