JavaScript: Map Object Tutorial
New in JS2015.
- Map objects are collections of key/value pairs. Each pair is called a “entry”.
- Key can be any Value Types.
- Value can be any value types.
- Keys are always distinct.
- The insertion order of entries are maintained.
The map object is designed to be used as a map data structure (similar to Python Dictionary or Ruby Hash Table or Java Map. ).
What is the difference between object and map?
- Map object's keys can be any type. Object's keys can be only string or symbol. [see Symbol Tutorial]
- The key/value pairs in map object are not properties. You don't have to worry about getting property key from parent object, or if a property is not enumerable. [see Access Property]
- Map object is designed to be used as a map data structure (aka hash table). For example, there's a “size” property to let you find number of entries, and there are proper methods to iterate thru the entries.
Create Map
new Map()
- Create a empty map.
new Map(iterable)
- Create a map from values in iterable object iterable.
[see Iterable]
const m = new Map(); // add new item m.set(1, "n1"); m.set(2, "n2"); console.log(m) // Map { 1 => 'n1', 2 => 'n2' }
There's no literal expression for map. But you can pass in a literal expression of array of array, like this:
new Map([ [key1, val1], [key2, val2] …])
const m = new Map([ [3, "n3"], [4, "n4"]]); console.log(m) // Map { 3 => 'n3', 4 => 'n4' }
Note: the map constructor (new Map()
) does not accept a object datatype.
[see Map Constructor]
[see Convert Object to/from Map]
Parent of Map Objects
The parent of any map object is Map.prototype
.
[see Prototype and Inheritance]
[see Map.prototype]
Set/Add Entry
map_obj.set(key, val)
[see Map.prototype.set]
Delete Entry
map_obj.delete(key)
[see Map.prototype.delete]
Check Key Existence
map_obj.has(key)
[see Map.prototype.has]
Get Key's Value
map_obj.get(key)
[see Map.prototype.get]
Size of Map
map_obj.size
[see Map.prototype.size]
Clear Map
Iterate Map
Get All Keys
Get All Values
Nested Map
const nestedMap = new Map([ ["tall", new Map([ ["old", new Map([["John",59751],["Mary",68534]])], ["young", new Map([["Joe",37235],["Smith",34426]])] ]) ], ["short", new Map([ ["old", new Map([["Jane",22328],["Connie",28459]])], ["young", new Map([["Jenny",67962],["David",69887]])] ]) ]]); console.log( nestedMap.get("tall").get("old").get("Mary") ); // 68534
Add Arbitrary Properties to Map
Because map is a object, you can add object properties to it, but you shouldn't do it.
const m = new Map([[3, "n3"], [4, "n4"], [5, "n5"] ]); // you can add arbitrary properties to a map object m.pp = 22; console.log(m.pp) // 22 console.log(Object.getOwnPropertyNames(m)); // [ 'pp' ]