javascript enum to convert to list and check if the value is present in that enum

Viewed 119

lets say i have an enum in javascript defined like this:

const myEnum = {
    A:'a',
    B:'b',
    C:'c',
    D:'d'
};

I have a character and I need to check whether it is present in the enum or not.

currently, I'm doing something like

if(value !== myEnum.A || value !==myEnum.B || ......) {
   //FAILURE
}

this is something of a problem how do I make it something like:

if(value not in myEnum.values){
   //FAILURE
}
1 Answers

you can use Object.values to check this

if (!Object.values(myEnum).includes(value)) {
    // Do what you want here
}

const myEnum = {
    A: 'a',
    B: 'b',
    C: 'c',
    D: 'd'
};

console.log(Object.values(myEnum).includes('a'));
console.log(Object.values(myEnum).includes('v'));

Related