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

Time:02-23

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
}

CodePudding user response:

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