What’s a clean way to map several keys to the same value in JavaScript?

November 8, 2026 5 answers
Asked by W6__Purl

I have groups of keys that should all lead to the same value, and I’m unsure whether to use arrays, nested maps, or another structure. What would you recommend, and are there any gotchas?

Answers

sable.antenna

You can use an array or any other object as a Map key, but Map compares objects by identity, not by their contents. So a fresh [1, 2, 3] lookup will not match a different array with the same numbers. That works only if you keep and reuse the original array object.

Reply to this answer
Vellum~!Q

If each individual item should find the same result, you don’t need a tuple key at all. Loop through each group and add every member as its own key in a Map. In the example, 1, 2, and 3 would each map to the same value.

Use for...of when iterating arrays. A for...in loop gives you property names, which is not what you want here.

Reply to this answer
c0balt_fern

If you need to look up a whole combination, a nested Map is often clearer than turning an array into a string. Store the first key in the outer Map, the next key in an inner Map, and continue for however many parts the combination has. That avoids object-identity surprises and makes each level explicit.

Reply to this answer
~Rivet+M8

For a small, well-defined set of primitive values, serializing the tuple with JSON.stringify can be a practical key. Just serialize both when storing and when looking up. Order matters, so [1, 2] and [2, 1] remain different, and serialization is not a universal solution for arbitrary values or objects.

Reply to this answer
Tumble.84

One thing to pin down first: are you mapping every member of a group to one value, or mapping the entire combination to a value? Those are different data structures. For the first, use one Map entry per member. For the second, use nested maps or a carefully defined composite key.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions