javascript

Map Object Type


Map object is used to create a collection of key-value pairs where both the keys and the values can be of any type, including objects.

 

Example:

// Map object
// Creating a new Map
let personMap = new Map();

// Adding key-value pairs to the Map
let obj1 = { name: "Rohit" };
let obj2 = { name: "Wasif" };

personMap.set(obj1, 25); // obj1 is the key, 25 is the value
personMap.set(obj2, 23); // obj2 is the key, 23 is the value

// Accessing values using keys
console.log(personMap.get(obj1)); // Output: 25
console.log(personMap.get(obj2)); // Output: 23

 

Explanation:

We create a Map called personMap, then use the set() method to add key-value pairs where the keys are objects (obj1 and obj2) and the values are numbers (25 and 30). Later, we can use the get() method to retrieve the values associated with the keys.