Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can write your own helper to transform a less verbose input into the more verbose 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()])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading