3

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

3
  • I think you want to create two maps a -> b -> 5 (in your example). Am I right? Commented Jul 10, 2017 at 10:26
  • @Ori Dor and, Jonasw, the sequence may matter, as the array will be again constructed, and the OP wants to make the combination as a key, so better to sort before stringify Commented Jul 10, 2017 at 10:52
  • @Jonasw yes, might be, the sequence also can be a part of the key, so completely depend on use case. :) Commented Jul 10, 2017 at 11:42

1 Answer 1

4

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Pretty neat solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.