What's the best way to use 2 string variables as the key for a Map?
const map = new Map();
map.set(['a', 'b'], 5);
map.get(['a', 'b']); //undefined
Creating a reference to [v1, v2] and using that as key is not an option for my case.
Is the only option to combine the two variables with a delimiter? (will be messy if the string variables can potentially contain the delimiter character).
May nest the Map:
var map=new Map();
function set(key1,key2,value){
if(map.has(key1)){
return map.get(key1).set(key2,value);
}
return map.set(key1,new Map([[key2,value]]));
}
function get(key1,key2){
if(map.has(key1)){
return map.get(key1).get(key2);
}
return false;
}
set("a","b","value");
console.log(get("a","b"))
If you want a variable length of keys, you may recursively create Maps and add an exit delimiter at the end, probably a symbol:
var exit=Symbol("exit");
set("a",exit,"value");
set("a","b",exit,"value");
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