Related Tags

Using Map data structure in ES6


Prior to the introduction of Maps in ES6, objects were generally used to hold key-value pairs. Maps have advantages over objects when creating hash maps because:

  • You can use different data types (i.e., primitives, objects, functions) as keys.
  • You can easily get the size of a map through it’s size property.
  • They are iterable; hence,​ you can easily loop through and manipulate them.

Note: an object can be iterated over as well, but not without the trickery of first converting it to an array, or checking to see if the property being iterated over belongs to it and not a prototype.

Usage

set() - add/update a key-value entry.

var movie = new Map();
movie.set('name', 'If Beale Street Could Talk');
movie.set('rating', 5);
movie.set(1, 'Test to show a number can be used as a key');

get() - returns a value mapped to a specified key.

console.log(movie.get('name')); //If Beale Street Could Talk
console.log(movie.get('rating')); //5
console.log(movie.get(1)); //Test to show a number can be used as a key

has() - returns a boolean indicating if a specified key exists or not.

console.log(movie.has('rating')); //true

forEach() - executes a provided function for each key/value pair.

movie.forEach( (value, key) => console.log(`this ${key} is mapped to ${value}`) );
//name is mapped to "If Beale Street Could Talk"
//rating is mapped to "5"
//1 is mapped to "Test to show a number can be used as a key"

keys() - returns a new iterator object that contains the key of each element.

for (let key of movie.keys()) {
  console.log(key);
}
// name
// rating
// 1

values() - returns a new iterator object that contains the value of each element.

for (let value of movie.values()) {
  console.log(value);
}
// If Beale Street Could Talk
// 5
// Test to show a number can be used as a key

entries() - returns a new iterator object that contains the [key, value] pairs of each element.

for (let [key, value] of movie.entries()) {
  console.log(`${key} » "${value}"`);
}
// name » "If Beale Street Could Talk"
// rating » "5"
// 1 » "Test to show a number can be used as a key"

delete() - removes specified element(s) from Map object.

console.log(movie.delete('rating')); //true
console.log(movie.has('rating')); //false

clear() - removes all elements in Map object.

console.log(movie.size) //2
movie.clear();
console.log(movie.size) //0

For more information, reference MDN web docs (by Mozilla).

RELATED COURSES
View all Courses