javascriptarraysdictionaryecmascript-6es6-map

Using Array objects as key for ES6 Map


I am trying to update my code to ES6 as I am using Node 4.0 and really like its features so far. However I have problems with the new ES6 Map data structure as it behaves differently to {} when using Array as a key. I am using it as a counter map.

I run this code and I would like to know how I can use arrays as keys for the 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']]);

It prints out the following and the first line should be 1 and not undefined:

undefined
1

The original JS map stringifies the key and I am not wanting to do the same type of stringify hack with the new ES6 Map.

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


Solution

  • Understand that ES2015 Map keys are compared (almost) as if with the === operator. Two array instances, even if they contain the same values, do not ever compare as === to each other.

    Try this:

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

    Since the Map class is intended to be usable as a base class, you could implement a subclass with an overriding .get() function, maybe.

    (The "almost" in the first sentence is to reflect the fact that Map key equality comparison is done via Object.is(), which doesn't come up much in daily coding. It's essentially a third variation on equality testing in JavaScript.)