In this article we will learn how to update an element in a map.
It is very common to update an element in a map in JavaScript.
Problem
Now we have a problem, which is that we want to update the value in the map
Imagine we have a map like this:
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
console.log(map);
// Map(2) { 'name' => 'John', 'age' => 30 }
And we want to update these values to become like this:
Map(2) { 'name' => 'Doe', 'age' => 60 }
How to solve this problem?
Fortunately, we have a built-in function that add elements to map called set.
Update elements in a map using set method
We can use set to update our map values.
set can update or add element to a map, in our example we will use it for update values.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Before updating
console.log(map);
// Update values
map.set('name', 'Doe');
map.set('age', 60);
// After updating
console.log(map);
Output
Map(2) { 'name' => 'John', 'age' => 30 }
Map(2) { 'name' => 'Doe', 'age' => 60 }
If the key does not exist, the function will add a new element to the map
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Update exists elements:
map.set('name', 'Doe');
map.set('age', 60);
// Add new element
map.set('country', 'USA');
// Print result:
console.log(map);
Output
Map(2) { 'name' => 'John', 'age' => 30 }
Map(3) { 'name' => 'Doe', 'age' => 60, 'country' => 'USA' }
Thank you for reading
Thank you for reading my blog. 🚀 You can find more on my blog and connect on Twitter
Top comments (0)