TypeScript Map Object
Map is a new data structure introduced in ES6 that is similar to objects, also being a collection of key-value pairs. However, compared to regular objects, Map provides more powerful and flexible functionality, especially regarding key types.
Using Map in TypeScript, you can combine it with generics to specify the types of keys and values, gaining complete type safety support.
Creating a Map
You can use the new Map() constructor to create a new Map. You can specify the types of keys and values.
// Create a Map with string keys and number values
let studentScores = new Map<string, number>();You can also initialize data directly when creating, through an array containing key-value pairs (like an array of tuples).
let initialScores: [string, number][] = [["Alice", 95], ["Bob", 88], ["Charlie", 100]];
let studentScores = new Map<string, number>(initialScores);Main Features of Map
- Keys of any type: Regular object keys can only be strings or Symbols. But
Mapkeys can be values of any type, including functions, objects, or any primitive type. - Ordered: Elements in a
Mapare arranged in insertion order. When you iterate over aMap, it will be in the order elements were added. sizeproperty:Mapdirectly provides asizeproperty to get the number of key-value pairs, which is more efficient than counting object properties.- Easy to iterate:
Mapnatively supports iteration and can be used directly withfor...ofloops.
Common Methods and Properties of Map
set(key, value)
Adds or updates a key-value pair in the Map. Returns the Map object itself, so it can be chained.
studentScores.set("David", 92);
studentScores.set("Alice", 98); // Update Alice's score
console.log(studentScores);
// Map(4) { 'Alice' => 98, 'Bob' => 88, 'Charlie' => 100, 'David' => 92 }get(key)
Gets the value corresponding to the specified key. Returns undefined if the key doesn't exist.
let bobScore = studentScores.get("Bob");
console.log(bobScore); // 88
let eveScore = studentScores.get("Eve");
console.log(eveScore); // undefinedhas(key)
Checks if the specified key exists in the Map, returns a boolean value.
console.log(studentScores.has("Charlie")); // true
console.log(studentScores.has("Frank")); // falsedelete(key)
Deletes the specified key-value pair. Returns true if successfully deleted; otherwise returns false.
let didDelete = studentScores.delete("Bob");
console.log(didDelete); // true
console.log(studentScores.has("Bob")); // falseclear()
Clears the Map, removing all key-value pairs.
studentScores.clear();
console.log(studentScores.size); // 0size Property
Returns the number of key-value pairs in the Map.
// Re-add data
studentScores.set("Anna", 99);
studentScores.set("Ben", 91);
console.log(studentScores.size); // 2Iterating Over a Map
Map provides multiple ways to iterate.
Using for...of Loop
This is the most commonly used iteration method.
for (let [key, value] of studentScores) {
console.log(`${key}'s score is ${value}`);
}
// Anna's score is 99
// Ben's score is 91Using forEach() Method
studentScores.forEach((value, key) => {
console.log(`${key}: ${value}`);
});Iterating Over Keys or Values
keys(): Returns an iterator containing all keys.values(): Returns an iterator containing all values.entries(): Returns an iterator containing all[key, value]pairs (for...ofinternally uses this).
// Iterate over keys
for (let key of studentScores.keys()) {
console.log(key);
} // Anna, Ben
// Iterate over values
for (let value of studentScores.values()) {
console.log(value);
} // 99, 91