JavaScript Map Reference Manual
Map is a data structure that stores key-value pairs, where the key can be any data type.
Map will remember the original insertion order of keys.
Map Methods and Properties
Method/Property | Description |
---|---|
new Map() | Create a new Map object. |
clear() | Removes all elements from the Map. |
delete() | Removes elements from the Map by key. |
entries() | Returns an iterator object containing [key, value] pairs in the Map. |
forEach() | Calls a callback function for each key/value pair in the Map. |
get() | Gets the value of a specific key in the Map. |
groupBy() | Groups object elements based on the value returned by the callback function. |
has() | Returns true if a key exists in the Map. |
keys() | Returns an iterator object containing the keys in the Map. |
set() | Sets a value for a specific key in the Map. |
size | Returns the number of elements in the Map. |
values() | Returns an iterator object containing the values in the Map. |
Instance
// Create Map ]
Example 2
You can use set()
Methods to add elements to Map:
// Create Map const fruits = new Map(); // Set the value of Map fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200);
Example 3
You can use get()
Methods to get elements from Map:
// Get the value of "apples" let value = fruits.get("apples"); JavaScript Objects vs Maps
The difference between JavaScript objects and Map
The difference between JavaScript objects and Map:
Object | Map |
---|---|
Cannot be iterated directly | Can be iterated directly |
Size attribute does not exist | Size attribute exists |
Keys must be strings (or symbols) | Keys can be of any data type |
The order of keys is not clear | Keys are sorted in the order of insertion |
Default key exists | No default key |