Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map single key multiple values using new Map() - javascript

Tags:

javascript

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");
like image 640
Abhay Singh Avatar asked Jul 02 '18 07:07

Abhay Singh


2 Answers

 var myMap = new Map();

 myMap.set("1",["A"]);
 myMap.set("1",["B", ...myMap.get('1')]);
like image 127
Efe Avatar answered Nov 02 '22 11:11

Efe


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]]));
like image 39
Nina Scholz Avatar answered Nov 02 '22 10:11

Nina Scholz