DEV Community

Mohamed Ibrahim
Mohamed Ibrahim

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

2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay