Javascript - print the name of an enum from a value

20,142

Solution 1

You could iterate the keys and test against the value of the property.

var refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419},
    value = 1,
    key;

Object.keys(refractiveIndex).some(function (k) {
    if (refractiveIndex[k] === value) {
        key = k;
        return true;
    }
});
console.log(key);

ES6

var refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419},
    value = 1,
    key = Object.keys(refractiveIndex).find(k => refractiveIndex[k] === value);

console.log(key);

Solution 2

https://jsfiddle.net/1qxp3cf8/

use for...of to go through the object properties and check if it equals the value you're looking for.

refractiveIndex = {
  "vacuum": 1,
  "air": 1.000293,
  "water": 1.33,
  "diamond": 2.419
};

var value = 1;
for (prop in refractiveIndex) {
  if (refractiveIndex[prop] == value) {
    console.log(prop);
  }
}

if you wanted it as a function you could write it as this:

function SearchRefractive(myValue) {
    for (prop in refractiveIndex) {
      if (refractiveIndex[prop] == myValue) {
        return prop;
      }
    }
}
var value = 1;
SearchRefractive(value);
Share:
20,142
Tyler
Author by

Tyler

Updated on November 01, 2020

Comments

  • Tyler
    Tyler over 3 years

    Is there a way I can print the values of the enum field given the int value? for example I have the following enum:

    refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419};
    

    If I have a value, is there a way to print the name of the enum. For example lets say I have a variable set to 1 and I want to print out "vacuum", how do I do that:

    var value = 1;
    console.log(refractiveIndex(value)); // Should print "vacuum" to console
    

    ?