3

Im using this 'map' on js:

   var myMap = new Object();
   myMap[key1]=value1; //like this n times...

but i want to use the key as some combination of two strings meaning:

  function getMapValue(str1,str2){...}

i dont mind joining the two strings into one long string and use the function with the long string

any ideas?

2
  • 1
    I'm not quite sure what it is you're asking here. Could you try clarifying your question, or providing a more complete example? Commented Dec 3, 2011 at 16:42
  • i just want to use this self generated map. and i want the key to be a string, or maybe transform the string into integer... just looking for an idea of how could it e done.. Commented Dec 3, 2011 at 16:44

2 Answers 2

3

You can make a map of maps (just be sure to check that the intermediate map exists when accessing it)

var myMap = {}; //dont use "new Object()". It is evil.

function insert(k1, k2, v){
   if(!(k1 in myMap)){ myMap[k1] = {}; }
   myMap[k1][k2] = v;
}

function get(k1, k2){
   return myMap[k1] && myMap[k1][k2];
}

And if you want to join two substrings into a single one you can use the plus operator to concatenate things.

var customKey = k1 + '|' + k2;

Just be sure your separator can't be used in a normal key to avoid conflicts.

Sign up to request clarification or add additional context in comments.

2 Comments

myMap[k1] && myMap[k1][k2] would return true or false, not the value of [k1][k2]
@jontro:In Javascript && returns the left operand if it is falsy and the right operand otherwise. This kind of use of && and || is a normal JS pattern.
0

If I got you right, the following should help:

var myMap = {"key1" : "something1", "key2" : "something2"};

to get value for a key, you you use, either: return myMap.key1;

Or: return myMap.["key1"];

If you had/did: myMap["key1key2"] = "MagicHappens!";

you could use myMap.key1key2 to get the value or myMap["key1key2"], or even: return myMap["key1"+"key2"];

Or:

var x = "key1";
var y = "key2";
return myMap[x+y];

in your getter function, you get the two variables for the keys which you can then directly use.

Comments

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.