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

52
Vistas
Javascript Map Object with multiple keys to one value

Is it possible to have multiple keys giving the same result in a JS Map, without having to write all of them ?

For example:

const mp = new Map<number, string>([
      [2 || 4, 'even'],
      [1 || 3, 'odd']
    ]);

This does not work but I am looking for something similar to avoid a switch case which is very verbose

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can write your own helper to transform a less verbose input into the one which new Map() expects:

const mapReducer = (arr, [keys, val]) => [
  ...arr,
  ...(Array.isArray(keys)
    ? [...keys.map(key => [key, val])]
    : [[keys, val]]
  )
];

const mp = new Map([
  [[2, 4], 'even'],
  [[1, 3], 'odd'],
  [0, 'meh...']
].reduce(mapReducer, []));

console.log([...mp.entries()])

about 4 years ago · Juan Pablo Isaza Denunciar

0

Is it possible to have multiple keys giving the same result in a JS Map, without having to write all of them ?

No. A map is a 1:1 connection between a key and a value. If you want two different keys to have the same value, that means you need to create two entries in the map.

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