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 iterate through the map:
function map_test(value) {
var myMap = {"one": 1, "two": 2, "three": 3};
for (key in myMap) {
if (myMap[key] == value) {
alert(key);
break;
}
}
}
Is there some function like Java's Map.getKey()
or a better way of getting keys?
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{
return false;
}
}
I dont think you need any function to get the value of a specific key.
You just have to write
var value = myMap[key];
for your specific case there is a faster solution:
function map_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()
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