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
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
Share Improve this question edited Jan 13, 2022 at 11:11 ikhvjs 5,9774 gold badges21 silver badges51 bronze badges asked Jan 13, 2022 at 11:03 AulomaAuloma 1531 gold badge3 silver badges11 bronze badges 5-
1
This looks like an XY-problem. What is the task you're doing with
switch
? (It probably is not an even-odd-check, which can be done easily without a map.) – Teemu Commented Jan 13, 2022 at 11:12 - Does this question help? stackoverflow./q/14743536/14032355 – ikhvjs Commented Jan 13, 2022 at 11:13
- JavaScript maps can't have duplicate keys, they must all be unique. See related: stackoverflow./questions/3996135/… – msalla Commented Jan 13, 2022 at 11:16
- @moritzsalla OP is talking about different keys with the same value, not for different values with the same key. – VLAZ Commented Jan 13, 2022 at 11:21
- 1 I try to map a type with a string. Some types can get the same string – Auloma Commented Jan 13, 2022 at 11:26
2 Answers
Reset to default 4You 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()])
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.