Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object/array as key for Map

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).

like image 867
Avery235 Avatar asked Feb 15 '26 20:02

Avery235


1 Answers

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");
like image 109
Jonas Wilms Avatar answered Feb 17 '26 08:02

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!