DEV Community

Mohamed Ibrahim
Mohamed Ibrahim

Posted on • Updated on • Originally published at mo-ibra.com

How to update an element in a map - JavaScript

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 }
Enter fullscreen mode Exit fullscreen mode

And we want to update these values to become like this:

Map(2) { 'name' => 'Doe', 'age' => 60 }
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output

Map(2) { 'name' => 'John', 'age' => 30 }
Map(2) { 'name' => 'Doe', 'age' => 60 }
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output

Map(2) { 'name' => 'John', 'age' => 30 }
Map(3) { 'name' => 'Doe', 'age' => 60, 'country' => 'USA' }
Enter fullscreen mode Exit fullscreen mode

Thank you for reading

Thank you for reading my blog. 🚀 You can find more on my blog and connect on Twitter

Top comments (0)