Using Array Objects as a Key for ES6 Map

I am trying to upgrade my code to ES6 as I am using Node 4.0 and really love its features so far. However, I am having problems with the new ES6 Map data structure, as it behaves differently with {} when using Array as the key. I use it as a counter card.

I am running this code and I would like to know how I can use arrays as keys for Map .

 "use strict"; var a = new Map(); a.set(['x','y'], 1); console.log(a.get(['x','y'])); var b = {}; b[['x','y']] = 1; console.log(b[['x','y']]); 

Prints the following, and the first line should be 1 , not undefined :

 undefined 1 

The original JS card builds the key, and I don't want to do the same type of stringify hack with the new ES6 Map .

What can I do to use arrays as keys reliably for ES6 Map ?

+6
source share
2 answers

Understand that ES2015 card keys are compared as if with the === operator. Two instances of an array, even if they contain the same values, are never compared as === each other.

Try the following:

 var a = new Map(), key = ['x', 'y']; a.set(key, 1); console.log(a.get(key)); 

Since the Map class is intended to be used as a base class, you can implement a subclass with an overriding function .get() , possibly.

+9
source

You need to keep a reference to the non-primitive Array instance that you used as the key. Note the difference in the following two examples:

 "use strict"; var a = new Map(); a.set(['x','y'], 1); console.log(a.get(['x','y'])); console.log(['x','y'] === ['x','y']); var b = new Map(); var array = ['x','y']; b.set(array, 1); console.log(b.get(array)); console.log(array === array); 
+1
source

All Articles