This succinct and straightforward article will show you how to add/remove key-value pairs to/from a Map in modern JavaScript. Without any further ado, let’s get to the point.
Adding key-value pairs to a Map
You can add a key-value pair to a Map by using the set() method. The syntax is as follows:
myMap.set(key, value)The set() method returns the same Map object, so you can chain multiple calls to it. If you pass a key that already exists in the Map, the old value associated with that key will be updated by the new value.
Example:
// Create a new Map object
let myMap = new Map();
// Add a string key and value
myMap.set('name', 'Sling Academy');
// Add a number key and value
myMap.set(1, 'one');
// Add a boolean key and value
myMap.set(true, 'yes');
// Chain multiple calls to the set() method
myMap.set('a', 'Apple').set('b', 'Banana').set('c', 'Coconut');
console.log(myMap);Output:
Map(6) {
'name' => 'Sling Academy',
1 => 'one',
true => 'yes',
'a' => 'Apple',
'b' => 'Banana',
'c' => 'Coconut'
}Removing key-value pairs from a Map
The delete() method can help you you remove a specific element from a Map by its key. It returns true if the element existed and was removed, or false if the element did not exist.
Example:
// Create a new Map object
let myMap = new Map([
['key1', 'value1'],
['key2', 'value2'],
['sling', 'academy']
]);
// remove elemnts whose key is 'key1' and 'key2'
myMap.delete('key1');
myMap.delete('key2');
console.log(myMap)Output:
Map(1) { 'sling' => 'academy' }In case you want to empty a Map (vacate all its elements), the clear() method is convenient. It returns undefined.
Example:
// Create a new Map object
let myMap = new Map([
['key1', 'value1'],
['key2', 'value2'],
['sling', 'academy']
]);
// remove all key-value pairs from the map
let result = myMap.clear();
console.log(result);
console.log(myMap)Output:
undefined
Map(0) {}