I need to map single key with multiple values using Map(). But my values keep on getting overwritten. Help.
var myMap = new Map();
myMap.set("1","A");
myMap.set("1","B");
var myMap = new Map();
myMap.set("1",["A"]);
myMap.set("1",["B", ...myMap.get('1')]);
You could take a Set
for multiple values for a key of a map.
function setValue(map, key, value) {
if (!map.has(key)) {
map.set(key, new Set(value));
return;
}
map.get(key).add(value);
}
var myMap = new Map();
setValue(myMap, "1", "A");
setValue(myMap, "1", "B");
console.log(Array.from(myMap.entries(), ([k, v]) => [k, [...v]]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With