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
?
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
?
Share Improve this question asked Nov 22, 2016 at 22:29 user2417339user2417339 2- So you basically want to switch the keys and the values in your original object? – user2345 Commented Nov 22, 2016 at 22:32
- 1 What if there are two elements with the same refractive index? – Barmar Commented Nov 22, 2016 at 22:41
2 Answers
Reset to default 13You 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);