Language: EN

como-usar-map-en-javascript

The Map Type in JavaScript

A Map is a collection that allows us to store key-value pairs, introduced in the ECMAScript 6 standard.

Unlike objects (Object) (which also store key-value pairs), Map offers several advantages in terms of performance and functionality. These are.

  • Keys of any type, keys can be of any type (not just strings or symbols)
  • Order, they maintain the insertion order.
  • Size property, which indicates how many key-value pairs it contains.
  • Easily iterable, we can easily iterate through its elements.
  • Better performance, for insertion and deletion operations.

Creating a Map

To create a Map, we simply use the class constructor:

const map = new Map();

Here we have created an empty Map, ready to store key-value pairs.

We can also initialize a Map with an iterable collection of key-value pairs:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  [3, 'value3']
]);

Basic Usage of Map

Adding key-value pairs

To add elements to a Map, we use the .set() method:

const myMap = new Map();

// Adding keys and values
myMap.set("key1", "value1");
myMap.set(2, "value2");
myMap.set({ object: "key" }, "value3");

console.log(myMap);
// Map(3) { 'key1' => 'value1', 2 => 'value2', { object: 'key' } => 'value3' }

Each call to .set() overwrites the value if the key already exists.

Accessing values

To get the value associated with a key, we use the .get() method:

console.log(myMap.get("key1")); // 'value1'
console.log(myMap.get(2)); // 'value2'

// Using an object as a key
const objectKey = { object: "key" };
myMap.set(objectKey, "new value");
console.log(myMap.get(objectKey)); // 'new value'

Checking if a key exists

We can use the .has() method to check if a key is present in the Map:

console.log(myMap.has("key1")); // true
console.log(myMap.has("nonExistentKey")); // false

Removing elements

To remove a specific element, we use .delete():

myMap.delete(2);
console.log(myMap); // Map(2) { 'key1' => 'value1', { object: 'key' } => 'new value' }

To remove all elements, we use .clear():

myMap.clear();
console.log(myMap); // Map(0) {}

Iteration Methods

Map offers several ways to iterate:

Using .forEach()

The .forEach() method allows us to iterate over all key-value pairs in a Map:

myMap.forEach((value, key) => {
  console.log(`Key: ${key}, Value: ${value}`);
});
// Output:
// Key: a, Value: 1
// Key: b, Value: 2
// Key: c, Value: 3

Using a for...of loop

We can also use a for...of loop with the .entries(), .keys(), or .values() methods:

// Iterate over entries
for (const [key, value] of myMap.entries()) {
  console.log(`Key: ${key}, Value: ${value}`);
}

// Iterate over keys
for (const key of myMap.keys()) {
  console.log(`Key: ${key}`);
}

// Iterate over values
for (const value of myMap.values()) {
  console.log(`Value: ${value}`);
}

Practical Examples