user1031947
user1031947

Reputation: 6674

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") ?

Upvotes: 0

Views: 70

Answers (2)

Guffa
Guffa

Reputation: 700850

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

Upvotes: 1

gdoron
gdoron

Reputation: 150313

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

Upvotes: 3

Related Questions