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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read 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