Javascript's Equivalent Of Java's Map.getkey()
I have a map or say an associative array kind of structure in JavaScript: var myMap = {'one': 1, 'two': 2, 'three': 3}; To get keys corresponding to a given value I have to iterat
Solution 1:
var myMap = {"one": 1, "two": 2, "three": 3};
declare it as a global variable
function getKey(value){
var flag=false;
var keyVal;
for (key in myMap){
if (myMap[key] == value){
flag=true;
keyVal=key;
break;
}
}
if(flag){
return keyVal;
}
else{
returnfalse;
}
}
I dont think you need any function to get the value of a specific key.
You just have to write
varvalue = myMap[key];
Solution 2:
for your specific case there is a faster solution:
functionmap_test(key,value)
{
var myMap = {"one": 1, "two": 2, "three": 3};
if(myMap.hasOwnProperty(key)) alert(key);
}
map_test('two',2);
In general, there isn't a direct method getKeys()
Solution 3:
about several months ago I wrote a wrapper to the native key value storage very similar to Java Map. Maybe it will be usefull to you, but remember getKey uses linear search because this is not a HashMap.
You can check the description and code of the class on my blog (cause it is a long code of only sugar methods): http://stamat.wordpress.com/javascript-map-class/
Solution 4:
You don't need such function, just write myMap[key]
, that's it.
Post a Comment for "Javascript's Equivalent Of Java's Map.getkey()"