I have a javascript object that maps ids:
codes = {
"admin" : 3,
"manager" : 2,
"basic" : 1
}
Given a value...
accountType = 2;
...what is the most elegant way to find the corresponding key ("manager") ?
for (var i in codes){
if (codes[i] == accountType)
alert(i);
}
jQuery version, though there is really no benefit from using it here:
$.each(codes, function(key, value){
if (value == accountType)
alert(key);
});
codes = { "3" : "admin", "2" : "manager", "1" : "basic" } you could have used this: codes["2"]If you do this a lot, it would be efficient to keep an object to use for the reverse lookup:
codeNames = {
"3": "admin",
"2": "manager",
"1": "basic"
}
Now you can just access the properties by name:
var name = codeNames[accountType];
You can create the lookup object from the codes object:
var codeNames = {};
for (var i in codes){
codeNames[codes[i]] = i;
}
{admin:2, manager:2}?