The JavaScript Map object is a built-in data structure that allows you to store key-value pairs in a collection, where each key can be of any type.
It preserves the insertion order of items, making it useful for maintaining data that needs to be ordered. This object provides various methods to add, retrieve, delete, and iterate over key-value pairs.
new Map([iterable])
Map objects can be created using the new Map()
constructor, which takes an optional iterable object (such as an array) as its argument.
JavaScript Map object example
A simple example code creates a new Map object.
<!DOCTYPE html>
<html>
<body>
<script>
let myMap = new Map();
// add key-value pairs
myMap.set("key1", "value1");
myMap.set("key2", "value2");
// retrieve a value
console.log(myMap.get("key1"));
// check if a key exists
console.log(myMap.has("key1"))
// retrieve the number of items
console.log(myMap.size)
</script>
</body>
</html>
Output:
You can iterate over the key-value pairs in the map using a for...of
loop:
<!DOCTYPE html>
<html>
<body>
<script>
let myMap = new Map();
// add key-value pairs
myMap.set("key1", "value1");
myMap.set("key2", "value2");
for (let [key, value] of myMap) {
console.log(key + " = " + value);
}
</script>
</body>
</html>
You can also use the forEach()
method to iterate over the key-value pairs:
myMap.forEach(function(value, key) {
console.log(key + " = " + value);
});
Use delete a key-value pair from the map using the delete()
method:
myMap.delete("key1");
Clear all key-value pairs from the map using the clear()
method:
myMap.clear();
Comment if you have any doubts or suggestions on this Js object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version