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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay