1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
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.
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.
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.const myMap = new Map();
myMap.set('name', 'John');
console.log(myMap.has('name')); // Output: true
console.log(myMap.get('name')); // Output: John
set()
The set()
method is the most straightforward way to update a value in a Map.
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’.Similar to objects, you can use bracket notation to update values in a Map.
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.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:
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:
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:
Can either use Map or Spread syntax to modify the array, and then assign it to the Map for the original key.
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.
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.
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]
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:
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.
Problem (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("
After 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:
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:
updateEmoji
function checks if the provided key exists in the Map using map.has(key)
.map.get(key)
.map.set(key, updatedValue)
.May your maps always be updated, and your Javascript journey is epic! 🗺🚀
Feel free to reach out!