Home  >  Q&A  >  body text

Using Array objects as keys in ES6 Map

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

I run this code and I want to know how to use an array as a key for a 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 the following, the first line should be 1 instead of undefined:

undefined
1

The original JS map stringifies the keys, and I don't want to do the same type of stringification hack with the new ES6 Map.

How can I reliably use arrays as keys in an ES6 Map?

P粉344355715P粉344355715364 days ago645

reply all(2)I'll reply

  • P粉529245050

    P粉5292450502023-10-22 13:33:57

    You need to save a reference to the non-primitive instance of the Array used as the key. Please 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);

    reply
    0
  • P粉978551081

    P粉9785510812023-10-22 11:23:32

    Understanding ES2015 Map key comparisons is (almost) like working with the === operator. Two array instances, even if they contain the same values, are not compared to each other in a === manner.

    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 used as a base class, you may be able to implement a subclass using an overridden .get() function.

    (The "almost" in the first sentence reflects that the Map key equality comparison is done through Object.is(), which rarely occurs in daily coding. Essentially, equality in JavaScript Third variant tested.)

    reply
    0
  • Cancelreply