Questions tagged [es6-map]

The ECMAScript 6 Map object holds key-value pairs that can be iterated through by looping. To use this tag, the post must be using ECMAScript 6 and must concern the use of how to use Map properly.

Syntax

To create a map:

const myMap = new Map();  //Map(0) 

This will create a new empty map object. The Map() constructor takes one optional parameter. For example, it can take an array of key/value pairs:

const myArr = [[1, 'one'], [2, 'two']];
const myMap = new Map(myArr);  //Map(2) {1 => "one", 2 => "two"}

This creates a map object with key 1 with a value of 'one' and key 2 with a value of 'two'. This is also possible with an iterable object:

const myIt = {
*[Symbol.iterator]() {
    yield [1, 'one'];
    yield [2, 'two'];
}};
const myMap = new Map(myIt); //Map(2) {1 => "one", 2 => "two"}

Again, this creates a map with the same structure as the last example.

Note that any value, from primitives to objects, can be used as either a key or a value. This includes NaN (Not a Number):

const myArr = [[NaN, 'one']];
const myMap = new Map(myArr);  //Map(1) {NaN => "one"}

This creates a map with a key of NaN with the value of "one". Even though NaNs are indistinguishable from each other, you cannot use them for multiple keys:

const myArr = [[NaN, 'one'], [NaN, 'two']];
const myMap = new Map(myArr);  //Map(1) {NaN => "two"}

This will only create one key of NaN where the last value associated with NaN will be in the map.

There are also getters and setters for the Map Object:

const myMap = new Map();  //Map(0)
myMap.set(1, "one");    //Map(1) {1 => "one"}
myMap.set(2, "two");    //Map(2) {1 => "one", 2 => "two"}
myMap.get(1);           //one
myMap.get(2);           //two

You can also create a map with mixed keys:

const myMap = new Map();
myMap.set(1, "one");
myMap.set("two", 2);
myMap.set(function () { return 3; }, "three")

This will create a map with a key of integer 1 with string value "one", a key of string "two" with an integer value of 2, and a key of an anonymous function with a string value of "three". However, while this works with setting, getting the last key will be impossible unless you define it outside the map first:

const myFunc = function () { };
const myMap = new Map();
myMap.set(1, "one");
myMap.set("two", 2);
myMap.set(myFunc, "three")
myMap.get(myFunc);    // three

To iterate through the map, you can use destructuring with the for...of loop:

for (var [key, value] of myMap) {
    console.log(key + ' = ' + value);
}

Or the forEach loop can be used as well:

myMap.forEach(function(value, key) {
    console.log(key + ' = ' + value);
});

Both examples will output the keys along with their values.

Reference

developer.mozilla.org

91 questions
4
votes
3 answers

Sort a Map by a property of values while keeping the keys

I have a map that’s declared like var cars = new Map();, where the string is the model of the car and the object has information like year and price. Therefore, the Map will look like this: Map = [ 'BMW' => { id:…
LostCoder
  • 51
  • 1
  • 1
  • 5
4
votes
4 answers

ES6 Map: transform values

I'm working on a project where I frequently have to transform every value in an ES6 map: const positiveMap = new Map( [ ['hello', 1], ['world', 2] ] ); const negativeMap = new Map(); for (const key of positiveMap.keys())…
NSjonas
  • 10,693
  • 9
  • 66
  • 92
4
votes
4 answers

Why should I use Map() when key is unknown until run time?

The MDN documentation on Map says: If you're still not sure which one to use [object or map], ask yourself the following questions: Are keys usually unknown until run time, do you need to look them up dynamically? [...] Those all are signs…
jpenna
  • 8,426
  • 5
  • 28
  • 36
3
votes
5 answers

How to access an (array) key in a JavaScript Map?

I'm looping through a two-dimensional array to set the values to a map. I'm storing the [i,j] indices as the map key, and the actual arr[i][j] value as the map value: const arrMap = new Map() for(let i = 0; i < arr.length; i++){ for(let j =…
Tzvi2
  • 182
  • 3
  • 14
3
votes
2 answers

How are ES6 maps implemented under the hood?

I was asked during an interview to implement a data structure of key/value pairs where keys can be an object, I know this is possible using ES6 maps but how do they work under the hood in Javascript where keys are strictly stringified and yet…
Khalid Khalil
  • 419
  • 1
  • 6
  • 14
3
votes
1 answer

Return fields by comparing to array of objects using Map Filter

Try to return field of array1 and another field of array2, on comparison. I have two array of objects (client and customer). I want to return client id and customer name where customer id is equal to client id.For this purpose I want to use…
Muhammad Nabeel
  • 111
  • 1
  • 14
3
votes
1 answer

How to look for changes in Map() when item is set or delete?

I am setting up a class for adding items to a shopping cart. The cart items are stored in a Map(). Now I want to save items as cookies, every time the map is changed. So when I call map.set() or map.delete() I want to fire a save function. But I…
xLittlePsycho
  • 87
  • 1
  • 10
3
votes
3 answers

How to use ES6 map function in React stateless component

In my React application, I have an array of objects which I get through an api response. I want to display each object detail in an accordion. I am using react-accessible accordion and have created a React Stateless Component. I want each of my…
techie_questie
  • 1,434
  • 4
  • 29
  • 53
3
votes
1 answer

How to have multiple identifiers for the same entity in normalizr?

What would you do, if you had a normalized redux store and using ids for entities, but also have other additional unique identifiers and need to use them as well. Example { entities: { users: { 1: { name: 'foo', …
farukg
  • 523
  • 4
  • 12
3
votes
2 answers

Why doesn't the Map size property update when I add a key/value pair using bracket notation?

According to MDN, the size property of a Map object should represent the number of entries the Map object has. However, if I create an empty Map and use the bracket notation (not sure what the formal name for this is) to add a key/value pair, the…
Ian
  • 5,704
  • 6
  • 40
  • 72
3
votes
1 answer

Using a value convertor on an ES 6 Map in Aurelia

I'm trying to sort a Map using a value convertor on a repeat-binding in Aurelia: Original code:
${obj.SomeProperty}
This works as expected, the values of the map are displayed and when I add…
Kenneth
  • 28,294
  • 6
  • 61
  • 84
2
votes
2 answers

Is there a difference between iterating a Map directly and via an iterator returned by entries()?

If I have a Map in JavaScript, e.g const myMap = new Map() myMap.set(0, 'zero') myMap.set(1, 'one') Then both of these two seem to be valid to iterate through the key-value pairs (and many other options which I am currently not interested in): //…
v-moe
  • 1,203
  • 1
  • 8
  • 25
2
votes
1 answer

Is there any advantage to using Object.create(null) over a Map?

I've seen people use code that looks like const STUFF_MAP = Object.create(null); STUFF_MAP would like suggested only be used like a map, so I understand why using Object.create(null) is better than {} (removing the properties that could cause…
Scrapper142
  • 566
  • 1
  • 3
  • 12
2
votes
2 answers

Can I preserve the order of a javascript object's entries, when some entry keys are integers?

I am working with an object where I need to preserve the order of the entries, even though some keys are alphanumeric and others are integers. (Yes, I know.) The object I'm starting with looks like this: { a: 'the', quick: 'quick', b:…
Rounin
  • 27,134
  • 9
  • 83
  • 108
2
votes
1 answer

Where are Map entries stored?

If I try to create a Map without calling the constructor, the object is unusable: const map = Object.create(Map.prototype); map.entries(); Out of curiosity, I wondered where the entries were stored but the constructor does not seem to add…
user3515941
  • 141
  • 1
  • 8