Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda