How to Update a Value in a Map in JavaScript
The Map object in JavaScript is a collection of key-value pairs where keys can be of any data type. A fundamental operation when working with a Map is to update the value associated with a specific key. This is a simple and direct process using the Map.prototype.set() method.
This guide will teach you how to use set() to update values, how to conditionally update a value based on its current content, and the correct patterns for updating nested arrays or objects stored within a Map.
The Core Method: Map.prototype.set()
The set() method is the primary tool for both adding new elements and updating existing ones in a Map.
Syntax:
myMap.set(key, newValue)
where:
key: The key of the element to add or update.newValue: The new value to associate with the key.
Problem
You have a Map and need to change the value for an existing key.
// Problem: Change the value associated with the 'status' key.
const userSettings = new Map([
['theme', 'dark'],
['status', 'online'],
]);
Solution:
const userSettings = new Map([
['theme', 'dark'],
['status', 'online'],
]);
// To update, simply call set() with the existing key and a new value.
userSettings.set('status', 'away');
console.log(userSettings.get('status')); // Output: 'away'
console.log(userSettings);
// Output: Map(2) { 'theme' => 'dark', 'status' => 'away' }
How set() Works for Adding and Updating
The set() method has a simple, dual-purpose behavior:
- If the provided
keyalready exists in theMap, it updates the value associated with that key. - If the provided
keydoes not exist in theMap, it adds the new key-value pair.
This makes the code for adding and updating identical, which simplifies your logic. You don't need to check if a key exists before setting its value.
const myMap = new Map();
// Adding a new key
myMap.set('color', 'blue');
console.log(myMap.get('color')); // Output: 'blue'
// Updating the existing key
myMap.set('color', 'red');
console.log(myMap.get('color')); // Output: 'red'
Conditionally Updating a Value
Sometimes, you need to update a value based on a condition. A common pattern is to first retrieve the value with get(), check it, and then use set() if the condition is met.
Solution: this example increments a counter in a Map only if it exists.
const analytics = new Map([
['pageViews', 150]
]);
const event = 'pageViews';
// Only update if the key exists
if (analytics.has(event)) {
const currentValue = analytics.get(event);
analytics.set(event, currentValue + 1);
}
console.log(analytics.get('pageViews')); // Output: 151
This map.has(key) is the best practice for checking if a key exists before trying to get its value. It returns true or false.
Updating a Nested Array or Object
When a Map value is an array or an object, you need to be careful to update it correctly, especially if you want to maintain immutability.
For example, you have a Map where a key holds an array, and you want to add a new item to that array.
// Problem: Add a new role to the user's 'roles' array.
const user = new Map([
['id', 101],
['roles', ['viewer']],
]);
The best practice is to get the current array, create a new array with the added item, and then set() the key to this new array. This avoids directly mutating the object stored in the Map.
const user = new Map([
['id', 101],
['roles', ['viewer']],
]);
// 1. Get the current array of roles.
const currentRoles = user.get('roles');
// 2. Create a new array with the old roles and the new one.
const updatedRoles = [...currentRoles, 'editor'];
// 3. Set the key to the new, updated array.
user.set('roles', updatedRoles);
console.log(user.get('roles')); // Output: ['viewer', 'editor']
This same pattern applies to objects:
const config = new Map([
['settings', { theme: 'dark', fontSize: 14 }]
]);
const currentSettings = config.get('settings');
const updatedSettings = { ...currentSettings, theme: 'light' };
config.set('settings', updatedSettings);
console.log(config.get('settings')); // Output: { theme: 'light', fontSize: 14 }
Conclusion
Updating a value in a JavaScript Map is a straightforward operation centered around the versatile set() method.
- To add or update a key-value pair, simply use
myMap.set(key, newValue). - To conditionally update a value, it's a good practice to first check for the key's existence with
myMap.has(key). - When updating a nested array or object, the recommended pattern is to get the existing value, create a new, updated version of it (often using spread syntax
...), and then useset()to associate the key with the new object.