1

I have an enum in which I store some UI element values that look like this:

const uiElementAttributes = {
   1: {
      id: 1,
      color: 'red',
      icon: 'icon-something.png'
   },
   2: {
      id: 2,
      color: 'yellow',
      icon: 'icon-something-else.png'
   },
   3: {
      id: 3,
      color: 'blue',
      icon: 'icon-this-item.png'
   },
   99: {
      id: 99,
      color: 'black',
      icon: 'icon-black.png'
   }
};

I have a function that will return the correct object from the enum based on id passed to my function. My question is how do I check if a value is defined in an enum?

Here's the function:

const getAttributes (id) => {

   // How do I check to see if the id is in the enum?
   if(checkIfIdIsInEnum) {
      return uiElementAttributes[id];
   } else {
      return uiElementAttributes[99];
   }

};

UPDATE: I'm trying the suggested answer. It does look pretty straight forward but looks like when webpack transpiles my code to vanilla JS, it adds default at the end of my enum which is undefined. Any idea what may be causing this -- see below? As you can see, the id value I'm passing is 1 so it should be able to find the value 1 in my enum object.

enter image description here

And here's the actual enum object: enter image description here

Here's the actual function code: enter image description here

UPDATE 2: I resolved the issue by importing the enum within curly braces -- see below:

import {calendarEvents} from '../../enums/calendarEvents';
Sam
  • 26,817
  • 58
  • 206
  • 383

1 Answers1

1

In this special case, you could access the property and if the result is falsey, then take the default property 99.

const getAttributes = id => uiElementAttributes[id] || uiElementAttributes[99];

Otherwise, you could use the in operator, or the suggested Object#hasOwnProperty.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392