简体   繁体   中英

Return name of object property by value in Javascript?

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);
}

Live DEMO

jQuery version, though there is really no benefit from using it here:

$.each(codes, function(key, value){
        if (value == accountType)
            alert(key);
});

Live DEMO

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM