0

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

2
  • What should happen with an object like {admin:2, manager:2}? Commented Mar 16, 2013 at 20:30
  • For mapping db values to something more readable. (I'm not interested in using a join table for this.) Commented Mar 16, 2013 at 20:34

2 Answers 2

3
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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I was wondering if there might be a way to do this without manually iterating through the properties
@user1031947, I'm afraid not. Sorry.
@user1031947, but if the object key value pairs were like: codes = { "3" : "admin", "2" : "manager", "1" : "basic" } you could have used this: codes["2"]
1

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

1 Comment

+1, though I think it's awful to have two objects to two different lookups. It can cause more pain than gain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.