Home > Back-end >  Can I use the same map key several times?
Can I use the same map key several times?

Time:02-05

I'm storing and retrieving data like this:

data = new Map();
data.set("key", id);
data.set("key", id2);
data.get("key");

the second set is overwriting key element. I want a structure, that can hold multiple times the key element or one key element with multiple id data pairs. Does such a collection exist in Javascript or how to achieve this?

thank you

CodePudding user response:

JS Map and no other JS structure I'm aware of allows you to have more occurences of the same key. Keys must be unique.

I think that maybe unshifting new values into an array stored in a regular object might be a good way to achieve what you want. That way, your newest value will always be the first in the array, and thus accessible at index 0, like so:

const data = {key: []};

data.key.unshift(id);
data.key[0] // value of id

data.key.unshift(id2);
data.key[0] // value of id2
  •  Tags:  
  • Related