Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!