In Typescript, the Map is a built-in object that allows us to store key-value pairs, where both the "keys" and "values" can be of any data type.
The Map is useful when we need to associate values with unique keys and perform operations such as "insertion", "retrieval", and "deletion" efficiently.
We can create a new Map by using the Map constructor.
let yourMap = new Map<string, number>();
This creates an empty map where keys are strings and values are numbers.
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3);
We can add key-value pairs to a `Map` using the `set` method.
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); let valueForKey3 = yourMap.get("key-3"); console.log("Key 3 Value", valueForKey3); // Returns 3
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); console.log(yourMap.has("key-10")); // Output: false
We can retrieve values from a `Map` using the `get` method.
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); yourMap.delete("key-1"); // Removes the entry with key "key-1" // Now your Map is left with key-2 and key-3. console.log(yourMap); // Output: Map (2) {"key-2" => 2, "key-3" => 3}
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); yourMap.delete("key-1"); // Removes the entry with key "key-1" // Now your Map Size is 2. console.log(yourMap.size); // Output: 2
We can check if a specific key is present in the `map` using the `has` method.
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); yourMap.clear(); // Removes all entries from the map console.log(yourMap) // Output: Map (0) {}
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); let convertArrayFromMap = [...yourMap]; // convert map into array. console.log(convertArrayFromMap) // Output: [["key-1", 1], ["key-2", 2], ["key-3", 3]]
We can remove key-value pairs from a `map` using the `delete` method.
let yourMap = new Map<string, number>(); yourMap.set("key-1", 1); yourMap.set("key-2", 2); yourMap.set("key-3", 3); yourMap.forEach((value, key) => { console.log(`${key}: ${value}`); // Output: "key-1: 1" // Output: "key-2: 2" // Output: "key-3: 3" });
We can get the number of entries in a `map` using the `size` property.
We can remove all entries from a `map` using the `clear` method
We can convert a map to an array using the spread operator.
We can iterate over the entries of a map using the forEach method.