When to use Object map vs Map class in ES6

Viewed 7282

Suppose I wanted to create a dictionary of, say, car makes to one or more models.

It seems that I could do this in two different ways in ES6.

1. Create an Object map:

Code:

const makesAndModels = {
    "mazda": [
        { name: "Miata" },
        { name: "626" }
    ],
    "toyota": [
        { name: "Camry" }
    ],
    ...
};

2. Create an ES6 Map instance:

Code:

const makes = {
    mazda: { name: "Mazda" },
    toyota: { name: "Toyota" }
};

const makesAndModels = new Map([
    [makes.mazda, [
        { name: "Miata" },
        { name: "626" }
    ]],
    [makes.toyota, [
        { name: "Camry" }
    ]],
    ...
]);

What are the key differences and pros/cons between the above two methods?

1 Answers

Here are the differences I've found thus-far:

  • Map allows you to use any type for the key. So if you want, you can store an entire object in the key, where, for an index signature, Typescript currently only supports string or number keys.

  • Map is only natively supported in ES6. If targeting ES5 or lower, you need to provide a polyfill.

Not sure if these are exhaustive though.

Edit: Just discovered an Objects and maps compared section in the Mozilla docs, which looks pretty comprehensive.

It includes the following items not mentioned above:

  • The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.

  • You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.

  • A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.

  • An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.

  • A Map may perform better in scenarios involving frequent addition and removal of key pairs.

Related