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");
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");
A Map data structure is a key/value store. A single key maps to a single value. So you must change the value if you want multiple:
var myMap = new Map();
myMap.set("1",["A","B"]);
Use an array of values, like above, in order to have a Map use a the key "1" to map to multiple value.
The second call to set in the OP, will overwrite the first value.
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]]));
You probably want the value to be an array. If you want to alter the value one at a time like you example, you need to get the value and then alter it.
var myMap = new Map();
myMap.set("1", []) //<-- '1' is now an empty array
myMap.get("1").push("A"); // <-- now add to the array
myMap.get("1").push("B");
console.log(myMap.get("1"))
console.log(myMap.get("1")[1]) // <-- just 'B'
Of course, there are lot of other ways of getting the values into the map.
m I iterate over all my key, value pairs.m.set([value ... m.get(key)])m.get(key) || []const keyval = [[2,3],[3,5],[3,8]]
m = new Map(); keyval.forEach(d=> m.set(d[0],[d[1],...m.get(d[0])||[]]));
returns:
Map(2) {2 => Array(1), 3 => Array(2)}
You can't do this in JavaScript until you have a unique key in that particular object.
Valid:
{
a: "1a23",
b: {
a: "23gh"
},
c: {
a: 34
}
}
Not Valid:-
{
a: "1a23",
a: "4354" //Not valid
b: {
a: "23gh",
a: "sdfd" //Not valid
},
c: {
a: 34
}
}
Cause if you try to get the property value of "a" how does the compiler figures out which is the one you are requesting. hence java Script overwrites if you have same property or if you try manually assigning it like this
let k = {
a: 1,
a:2
}
It will throw an error. so alternatively you can use an array to do this something like
let k = {
a: [1,2]
}
let k2 = myMap.set("a",[1,2]);