Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

Map

Object

Accidental Keys

A Map does not contain any keys by default. It only contains what is explicitly put into it.

An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful.

Key Types

A Map's keys can be any value (including functions, objects, or any primitive).

Key Order

The keys in Map are ordered in a simple, straightforward way: A Map object iterates entries, keys, and values in the order of entry insertion.

Although the keys of an ordinary Object are ordered now, this was not always the case, and the order is complex. As a result, it's best not to rely on property order.

Size

The number of items in an Object must be determined manually.

Iteration

Note:

Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Examples:

let myMap = new Map()
myMap.set(0, 'zero')
myMap.set(1, 'one')

for (let [key, value] of myMap) {
  console.log(key + ' = ' + value)
}
// 0 = zero
// 1 = one

for (let key of myMap.keys()) {
  console.log(key)
}
// 0
// 1

for (let value of myMap.values()) {
  console.log(value)
}
// zero
// one

for (let [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value)
}
// 0 = zero
// 1 = one
// Note: TypeScript has been used here to do this examples
const myVariable: Map<string, myModel> = new Map(name, myModelValues);

// Another example of the Map class
let myVariable: myModel[] = [{name: 'Hello', lastName: 'Bye'}];

interface myModel {
    name: string;
    lastName: string;
}

const myVariable2: Map<string, myModel> = new Map(myVariable.map(model => [model.name, model]));
const result = myVariable2.get('Hello');
console.log(result?.name);
console.log(myVariable); 

// Results
// [LOG]: "Hello" 
// [LOG]: [{
//  "name": "Hello",
//  "lastName": "Bye"
// }] 
let myVariable: myModel[] = [
    {name: 'Hello', lastName: 'Bye'},
    {name: 'Hey', lastName: 'Good bye'},
    {name: 'Hi', lastName: 'c-ya'}];

interface myModel {
    name: string;
    lastName: string;
}

const myVariable2: Map<string, myModel> = new Map(myVariable.map(model => [model.name, model]));
const result = myVariable2.get('Hello');

for(const [element, model] of myVariable2) {
    console.log(element); // Hello, hey, hi
    console.log(model); // The object that contains hello...
}

/**
 *  [LOG]: "Hello" 
    [LOG]: {
    "name": "Hello",
    "lastName": "Bye"
    } 
    [LOG]: "Hey" 
    [LOG]: {
    "name": "Hey",
    "lastName": "Good bye"
    } 
    [LOG]: "Hi" 
    [LOG]: {
    "name": "Hi",
    "lastName": "c-ya"
    }
 */

Last updated

Was this helpful?