7
c =      {
            "UNKNOWN_ERR" : 0,
            "INDEX_SIZE_ERR" : 1,
            "DOMSTRING_SIZE_ERR" : 2,
            "HIERARCHY_REQUEST_ERR" : 3,
            "WRONG_DOCUMENT_ERR" : 4,
            "INVALID_CHARACTER_ERR" : 5,
            "NO_DATA_ALLOWED_ERR" : 6,
            "NO_MODIFICATION_ALLOWED_ERR" : 7,
            "NOT_FOUND_ERR" : 8,
            "NOT_SUPPORTED_ERR" : 9}

To get the value using the key is easy, I just use the key in c["UNKNOWN_ERR"] to get 0, given that all the values are unique is safe to get the key (message) from the value(errorcode).

Is there a standard way to do that or do I need to write a function that looks in all key and search that specific value?

Eduard Florinescu
  • 16,747
  • 28
  • 113
  • 179
  • 1
    Possible duplicate of [best way to get the key of a key/value javascript object](http://stackoverflow.com/questions/6268679/best-way-to-get-the-key-of-a-key-value-javascript-object) – Andy Feb 04 '16 at 18:03
  • Probably a duplicate of https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value –  Jul 04 '19 at 10:29

4 Answers4

18

As you already assumed you need to iterate over the object's attributes and check the value.

for(var key in c) {
    if(c[key] === whatever) {
        // do stuff with key
    }
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
13

es6 find method:

const getKey = (obj,val) => Object.keys(obj).find(key => obj[key] === val);

in your case

console.log(getKey(c,1)); // INDEX_SIZE_ERR
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
6

Underscore provides a more easy solution to this

You can get key using this code also

var errKey = _.invert(c)[errCode];

for e.x. if you use errCode = 3 as shown below

var errKey = _.invert(c)[3];

then

errKey will be HIERARCHY_REQUEST_ERR

Pratik
  • 1,531
  • 3
  • 25
  • 57
2

Try findKey() lodash method:

var key = _.findKey(c, v => v === val)

where val - property value.

ns16
  • 1,322
  • 2
  • 17
  • 26