Using enums in react const

Viewed 5874

I need to map enum values to 1 variable and then call the variable and check if that enum was present or not.

render() {
    const {
        id,
        name,
        features} = this.props;
}

Features would be the variable that needs to be mapped according to which enums are coming in. I would get something similar from the API:

{"id":"111", "name":"jack", "features":["MOUNTAIN", "HILL"]}

So there would be a total of 4 different features : MOUNTAIN, HILL, LAKE, FISH.
Then when needed I can check:

if(features.mountain)
    //do stuff
1 Answers

If you like to check if a given property from your enum (for example "MOUNTAIN") is included in the features array returned from the api you can use the Array.prototype.includes() method:

if(featuresArrayfromApi.includes('MOUNTAIN'){
   //do stuff
} 

If you would like to check if the features returned from the api include one or more of the properties in your features enum you can combine includes with Array.prototype.some().

For example, in Typescript you would write it like this:

enum Features { MOUNTAIN, HILL, LAKE, FISH }

if(Object.keys(Features)
 .some(feature => featuresFromApi.includes(feature))){
   // do stuff
}

Edit

The features key from the api data should be mapped like any other key(id, name) - just instead of holding 1 value it holds an array. Then you can use the validations suggested above in an if clause. For example:

const data = [
    {"id":"111", "name":"jack", "features":["MOUNTAIN", "HILL"]},
    {"id":"222", "name":"john", "features":["FISH", "HILL", "LAKE"]}
    {"id":"333", "name":"joe", "features":["LAKE", "HILL", "FISH"]}

    ]

    data.map(record =>{

      console.log(record.id); 
      console.log(record.name);

      if (record.features.includes('MOUNTAIN'){
          // do stuff
        }          
    })

Also, bear in mind that enum is a Typescript symbol which isn't available in Javascript, so in case you are not using Typescript you can just declare it like this and it would work the same:

const Features =  { 
 MOUNTAIN: "MOUNTAIN",
 HILL: "HILL",
 LAKE, "LAKE",
 FISH: "FISH" 
}

Related