How to update a Value in a Map in JavaScript


JavaScript Maps provide an elegant way to store key-value pairs. But how do we update values in a Map. Whether you’re a JavaScript beginner or a seasoned developer, you will explore code samples for frequent cases, common errors, and a fun coding problem to polish your skills.


Understanding JavaScript Maps

A Map is a collection of key-value pairs where each key can be of any data type. Unlike objects, Maps maintain the insertion order of the keys, making them versatile for various scenarios.

Standard Map API functions

  • set(): The set() method adds or updates a key in a Map with a specified value.
  • has(): The has() method returns a boolean indicating whether the Map contains a specific key.
  • get(): The get() method retrieves the value associated with a key in the Map.
JavaScript
const myMap = new Map();

myMap.set('name', 'John');
console.log(myMap.has('name'));  // Output: true
console.log(myMap.get('name'));  // Output: John

2 Ways to Modify Value in Map

Method 1: Using set()

The set() method is the most straightforward way to update a value in a Map.

JavaScript
const myMap = new Map([
    ['name', 'John'],
    ['age', 25],
    ['city', 'New York']
]);

myMap.set('age', 26);

console.log(myMap.get('age')); // Output: 26

Explanation:

  • myMap.set('age', 26): Updates the value associated with the key ‘age’.

Method 2: Using Bracket Notation

Similar to objects, you can use bracket notation to update values in a Map.

JavaScript
const myMap = new Map([
    ['name', 'John'],
    ['age', 25],
    ['city', 'New York']
]);

myMap.set('age', 26);

console.log(myMap.get('age')); // Output: 26

Explanation:

  • myMap['city'] = 'San Francisco': Updates the value associated with the key ‘city’ using bracket notation.

3 Usual Scenarios of modifying Map value

Scenario 1: Conditionally Modifying Individual Values

Say you are storing Strings, Numbers, etc. inside Map values, and based on some condition you want to modify the value in map. You can do so as in below use cases:

Example: Regular Expression Match

JavaScript
const myMap = new Map([
    ['message', 'Hello World']
]);

const keyToUpdate = 'message';
const regex = /Hello/;

if (myMap.has(keyToUpdate) && regex.test(myMap.get(keyToUpdate))) {
    myMap.set(keyToUpdate, 'Greetings Earthling!');
}

console.log(myMap.get(keyToUpdate));  // Output: Greetings Earthling!

Explanation:

  • The value associated with the key ‘message’ is updated if it exists and matches the specified regular expression.

Example: Number Comparison

JavaScript
const myMap = new Map([
    ['temperature', 30]
]);

const keyToUpdate = 'temperature';
const threshold = 25;

if (myMap.has(keyToUpdate) && myMap.get(keyToUpdate) > threshold) {
    myMap.set(keyToUpdate, 'High Temperature');
}

console.log(myMap.get(keyToUpdate));  // Output: High Temperature

Explanation:

  • The value associated with the key ‘temperature’ is updated if it exceeds the specified threshold.

Scenario 2: Modifying Array Value Stored in a Map

Example: Modifying all values of the Array entry stored in Map

Can either use Map or Spread syntax to modify the array, and then assign it to the Map for the original key.

JavaScript
const myMap = new Map([
    ['fruits', ['apple', 'orange', 'banana']]
]);

const keyToUpdate = 'fruits';

// Map example:
const newMapExample= myMap.get(keyToUpdate).map(fruit => fruit.toUpperCase());
myMap.set(keyToUpdate, newMapExample);
console.log(myMap.get(keyToUpdate));  
// Output: ['APPLE', 'ORANGE', 'BANANA']

// Spread Syntax example:
const newSpreadExample = [...myMap.get(keyToUpdate), 'grape', 'kiwi'];
myMap.set(keyToUpdate, newArray);
console.log(myMap.get(keyToUpdate));  
// Output: ['APPLE', 'ORANGE', 'BANANA', 'grape', 'kiwi']

Explanation:

  • Map example: The array entry in the Map value is modified by converting all elements to uppercase.
  • Spread syntax example: The array entry in the Map value is modified by spreading the existing elements and adding ‘grape’ and ‘kiwi’ to the array.

Example: Conditionally modifying entries of the Array stored in Map

Can selectively modify entries in array and reassign to Map’s key. In following example, the array entry in the Map is filtered to include only even numbers.

JavaScript
const myMap = new Map([
    ['numbers', [1, 2, 3, 4, 5]]
]);

const keyToUpdate = 'numbers';
const evenNumbers = myMap.get(keyToUpdate).filter(number => number % 2 === 0);

if (evenNumbers.length > 0) {
    myMap.set(keyToUpdate, evenNumbers);
}

console.log(myMap.get(keyToUpdate));  // Output: [2, 4]

Scenario 3: Modifying Object Value Stored in a Map

JavaScript
const myMap = new Map([
    ['person', { name: 'John', age: 30 }]
]);

const keyToUpdate = 'person';
const updatedObject = { ...myMap.get(keyToUpdate), age: 31 };

myMap.set(keyToUpdate, updatedObject);

console.log(myMap.get(keyToUpdate));  // Output: { name: 'John', age: 31 }

Explanation:

  • The object entry in the Map value is modified by updating the ‘age’ property.

🧪Practice Coding Problem: Emoji Map Updater

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Write a function updateEmoji(map, key, emoji) that takes a Map, a key, and an emoji, and updates (or appends) the value associated with the key to include the provided emoji.

Note, in following example, only “happy” map entry got updated.

JavaScript
/**
 * Updates a value in the Map to include an emoji.
 * 
 * @param {Map} map - The Map to be updated.
 * @param {string} key - The key to update.
 * @param {string} emoji - The emoji to be added to the value.
 */
function updateEmoji(map, key, emoji) {
  // > > > 👉 Write code here 👈 < < <
}

// Driver code
const emojiMap = new Map([
    ['happy', '😊'],
    ['sad', '😢'],
    ['excited', '😃']
]);

console.log("Before Update:");
console.log("Happy Emoji:", emojiMap.get('happy')); // Output: 😊
console.log("Sad Emoji:", emojiMap.get('sad'));     // Output: 😢
console.log("Excited Emoji:", emojiMap.get('excited')); // Output: 😃

// Update the 'happy' key with a new emoji
updateEmoji(emojiMap, 'happy', '🎉');

console.log("\nAfter Update:");
console.log("Happy Emoji:", emojiMap.get('happy')); // Output: 😊🎉
console.log("Sad Emoji:", emojiMap.get('sad'));     // Output: 😢
console.log("Excited Emoji:", emojiMap.get('excited')); // Output: 😃
Please attempt before seeing the Answer:
JavaScript
function updateEmoji(map, key, emoji) {
    if (map.has(key)) {
        const currentValue = map.get(key);
        const updatedValue = currentValue + emoji;
        map.set(key, updatedValue);
    } else {
        console.error(`Key '${key}' not found in the Map.`);
    }
}

Explanation:

  1. The updateEmoji function checks if the provided key exists in the Map using map.has(key).
  2. If the key exists, it retrieves the current value associated with the key using map.get(key).
  3. It then concatenates the provided emoji to the current value and updates the Map using map.set(key, updatedValue).
  4. If the key is not found, an error message is logged to the console.

May your maps always be updated, and your Javascript journey is epic! 🗺🚀

Scroll to Top