To add a key-value pair to a map in TypeScript, you can use the set method.
We can add a key-value pair to a map in TypeScript using the set method, which adds or updates an element with a specified key and value.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.set
method to add a new key-value pair to the map. The set
method takes two arguments: the key and the value to be added.forEach
method and console.log
.let myMap: Map<string, number> = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Add a key-value pair using set method
myMap.set('four', 4);
// Print the updated map
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
one: 1 two: 2 three: 3 four: 4
We can add multiple key-value pairs to a map in TypeScript using the set method.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.set
method to add multiple new key-value pairs to the map. The set
method takes two arguments: the key and the value to be added.forEach
method and console.log
.let myMap: Map<string, number> = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Add multiple key-value pairs using set method
myMap.set('four', 4);
myMap.set('five', 5);
// Print the updated map
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
one: 1 two: 2 three: 3 four: 4 five: 5
We can update an existing key-value pair in a map in TypeScript using the set method, which updates the value of a specified key if it already exists.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.set
method to update the value of an existing key in the map. The set
method takes two arguments: the key and the new value to be assigned.forEach
method and console.log
.let myMap: Map<string, number> = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Update an existing key-value pair using set method
myMap.set('two', 22);
// Print the updated map
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
one: 1 two: 22 three: 3
In this tutorial, we learned How to Add a Key-Value Pair to a Map in TypeScript language with well detailed examples.