The other answers don't mention one last difference between objects and Map
s:
The Map
object holds key-value pairs and remembers the original insertion order of the keys.
Thus, when iterating over it, a Map object returns keys in order of insertion.
Quote from MDN, emphasis mine
This was the main reason I decided to use Map
for the first time in a recent project. I had a normal object that I needed to display in a <table>
, with each property going in a specific row.
let productPropertyOrder = [ "name", "weight", "price", "stocked" ];
let product =
{
name: "Lasagne",
weight: "1kg",
price: 10,
stocked: true
}
I wrote a function to transform an object into a Map
according to a desired key order:
Note: this function discards all object properties not found in order
function objectToMap( obj, order )
{
let map = new Map();
for ( const key of order )
{
if ( obj.hasOwnProperty( key ) )
{
map.set( key, obj[ key ] );
}
}
return map;
}
Then the map could be iterated over in the desired order:
let productMap = objectToMap( product, productPropertyOrder );
for ( const value of productMap.values() )
{
let cell = document.createElement( "td" );
cell.innerText = value;
row.appendChild( cell );
}
Of course this is a bit contrived because one could just as well display when iterating over the property order without creating a Map
in the process:
for ( const key of productPropertyOrder )
{
if ( product.hasOwnProperty( key ) )
{
let value = product[ key ];
// create cell
}
}
But if you have an array of such objects and are going to be displaying them many places, then converting them all to maps first makes sense.
map.set('foo', 123)
performed quicker thanobj.foo = 123
? If so that's very surprising