Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - print the name of an enum from a value

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

?

like image 528
Tyler Hilbert Avatar asked Nov 22 '16 22:11

Tyler Hilbert


People also ask

How do I find the name of an enum?

Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);

Can we get an enum by value?

Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.


2 Answers

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);
like image 112
Nina Scholz Avatar answered Sep 18 '22 12:09

Nina Scholz


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);
like image 23
zfrisch Avatar answered Sep 18 '22 12:09

zfrisch