kaushalpranav
kaushalpranav

Reputation: 2184

What is the best way to use a list as a key in JavaScript?

Let say we have a map in JS as below.

const someMap = new Map();

someMap.set(["Jack", "Mathematics"], "Fee=₹120000");
someMap.set(["Alyne", "Science"], "Fee=₹90000");


// Going to be undefined because the lists are compared by ===
console.log(someMap.get(["Jack", "Mathematics"]));

This prevents us from checking for keys in a map dynamically because of === comparison. One way I can think of is to convert it to a string like "Jack, Mathematics" and then use it as a key. But this doesn't look perfect.

What is the best way to represent keys which are lists? By best way, I mean a way where we preserve the list structure of the key. Let say we are converting the list ["adog", "isananimal"] to a string "adog,isananimal" and there is another list ["adog,isananimal"] which converts to the same string "adog,isananimal" which would create a confusion while retrieving the values.

Upvotes: 1

Views: 737

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

Stringification is still the most straightforward approach. If you don't like the implications of that, you can hide the implementation details in a custom class that extends Map:

class ArrayKeyedMap extends Map {
  get(array) {
    return super.get(this.#toKey(array));
  }
  
  set(array, value) {
    return super.set(this.#toKey(array), value);
  }
  
  has(array) {
    return super.has(this.#toKey(array));
  }
  
  delete(array) {
    return super.delete(this.#toKey(array));
  }
  
  #toKey(array) {
    return JSON.stringify(array);
  }
}

const someMap = new ArrayKeyedMap();

someMap.set(["Jack", "Mathematics"], "Fee=₹120000");
someMap.set(["Alyne", "Science"], "Fee=₹90000");

console.log(someMap.get(["Jack", "Mathematics"]));

If you want, you can take it further and override other Map functions like keys() and entries() as well using a custom #fromKey() function to map the strings back to arrays.

Upvotes: 3

Related Questions