![]() |
In this article, we will see different approaches to update the value for a specific key in Map in JavaScript. JavaScript Map is a collection of key-value pairs. We have different methods to access a specific key in JavaScript Map. Methods to update the value for a specific key in Map in JavaScriptTable of Content Method 1: Using JavaScript Map.set() methodIn this method, we will use the built-in Map.set() method to update the value for a specific key. Example: In this example. we will update the value of key(‘b’) in the given map using the map.set() method.
Output Old value for key: 'b', 200 New value for key: 'b', 1000 Method 2: Using Map.forEach() methodIn this method, we will iterate the map using map.forEach() method to iterate the key-value pairs and update the value for specific key. Example: In this example, we will iterate map using forEach method and update the value for a specific key using if condition.
Output Old value for key: 'b', 200 New value for key: 'b', 1000 Method 3: Using JavaScript Map.has() and Map.set() MethodsIn this method, we will first check if the Map contains the specific key using the has() method. If the key is present, we will then use the set() method to update its value. Example:
Output Old value for key: 'b', 200 New value for key: 'b', 1000 In this example, we will update the value of key (‘b’) in the given map only if it exists, using the has() and set() methods. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |