remove a key-value pair from a map in javascript

To remove a key-value pair from a Map object in JavaScript, you can use the Map.prototype.delete() method. This method removes the element associated with the specified key, if it exists.

Here's an example code snippet that demonstrates this:

index.tsx
// create a new Map object
const myMap = new Map();

// add some key-value pairs to the map
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');

// remove a key-value pair from the map
myMap.delete('key2');

// check if the pair still exists
console.log(myMap.has('key2')); // outputs: false
327 chars
14 lines

In this example, we create a new Map object myMap and add three key-value pairs using the set() method. Then we use the delete() method to remove the key-value pair with the key 'key2'. Finally, we check if the pair was successfully removed by calling the has() method with the same key, which returns false.

related categories

gistlibby LogSnag