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
?
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);
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With