In JavaScript, a Map
object is a data structure that allows you to store key-value pairs, where each key is unique and can be of any type.
To retrieve a value from a Map
object in JavaScript, you need to use the get()
method.
Here’s a detailed explanation of how to do it.
Creating a Map object
Before we can retrieve a value from a Map
object, we need to create one first. To create a new Map
object, we can use the Map()
constructor function like this:
const myMap = new Map();
This creates an empty Map
object called myMap
.
Adding key-value pairs to a Map object
To add key-value pairs to a Map
object, we can use the set()
method. The set()
method takes two arguments: the key
and the value
.
Here’s an example:
myMap.set("apple", 5);
myMap.set("banana", 10);
myMap.set("orange", 15);
In this example, we’ve added three key-value pairs to the Map
object. The keys are strings ("apple"
, "banana"
, and "orange"
), and the values are numbers (5
, 10
, and 15
).
Retrieving a value from a Map object
To retrieve a value from a Map
object, we need to use the get()
method. The get()
method takes one argument: the key
of the value we want to retrieve.
Here’s an example:
const appleCount = myMap.get("apple");
console.log(appleCount); // Output: 5
In this example, we’re retrieving the value associated with the key "apple"
from the Map
object. We’re storing the result in a variable called appleCount
, and then logging it to the console. The output should be 5
.
Handling non-existent keys
If we try to retrieve a value from a Map object using a key that doesn’t exist, the get()
method will return undefined
.
Here’s an example:
const pearCount = myMap.get("pear");
console.log(pearCount); // Output: undefined
In this example, we’re trying to retrieve the value associated with the key "pear"
from the Map
object. Since "pear"
is not a key in the Map object, the get()
method returns undefined
.
Retrieving multiple values from a Map object
If we want to retrieve multiple values from a Map object, we can use a loop to iterate over the keys and call the get()
method for each key.
Here’s an example:
for (const [key, value] of myMap) {
console.log(`${key} = ${value}`);
}
In this example, we’re using a for...of
loop to iterate over the key-value pairs in the Map
object. For each pair, we’re logging a string to the console that includes the key and the value.
The output of this code would be:
apple = 5;
banana = 10;
orange = 15;
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.