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?
Create Map
new Map()
- Create a empty map.
new Map(iterable)
- Create a map from values in iterable object iterable.
[see Iterable Object]
const xx = new Map(); // add new item xx.set(1, "n1"); xx.set(2, "n2"); console.log(xx); // 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 xx = new Map([[3, "n3"], [4, "n4"]]); console.log(xx); // 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
Delete Entry
Check Key Existence
Get Key's Value
Size of Map
Clear Map
Iterate Map
Get All Keys
Get All Values
Nested Map
const nestedMap = new Map([ [ "tall", new Map([ ["old", new Map([["John", 59], ["Mary", 68]])], ["young", new Map([["Joe", 37], ["Smith", 34]])], ]), ], [ "short", new Map([ ["old", new Map([["Jane", 22], ["Connie", 28]])], ["young", new Map([["Jenny", 67], ["David", 69]])], ]), ], ]); console.log(nestedMap.get("tall").get("old").get("Mary") === 68);
Add Arbitrary Properties to Map
Because map is a object, you can add object properties to it, but you shouldn't do it.
const xx = new Map([[3, "n3"], [4, "n4"], [5, "n5"]]); // you can add arbitrary properties to a map object xx.pp = 22; console.log(xx.pp === 22);