Validating an item within an enumeration

In my enum, I store various UI element values organized as follows:

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'
   }
};

My function is designed to retrieve the correct object from the enum based on the provided id. My inquiry revolves around determining how to ascertain if a value exists within the enum.

Below is the function in question:

const getAttributes = (id) => {

   // How can I validate if the id exists in the enum?
   if(checkIfIdIsInEnum) {
      return uiElementAttributes[id];
   } else {
      return uiElementAttributes[99];
   }

};

UPDATE: I have implemented the recommended solution. Although it initially appeared straightforward, a peculiar scenario arises when webpack transpiles my code to vanilla JS, appending 'default' at the end of my 'enum' leading to 'undefined'. Any insights on what might be triggering this issue -- exemplified below? The 'id' value being passed is '1', which should correspond to the value '1' within my enum object.

https://i.sstatic.net/QYRCm.png

Here is the exact 'enum' object snapshot: https://i.sstatic.net/Wlz1H.png

Actual function code snippet provided below: https://i.sstatic.net/njjha.png

UPDATE 2: I managed to resolve the issue by importing the enum within curly braces -- detailed below:

import {calendarEvents} from '../../enums/calendarEvents';

Answer №1

In this particular scenario, you have the option to retrieve the property and if the result turns out to be falsy, then default to the value of property 99.

const fetchAttributes = identifier => uiElementAttributes[identifier] || uiElementAttributes[99];

Alternatively, you may utilize the in operator, or consider using the recommended Object#hasOwnProperty.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preserving line breaks when sending a message through the mail

Hi, I'm currently facing an issue: I am trying to send text from a textarea using POST to a PHP script that will write it to a file and display it on the website. However, when I do this, the line breaks disappear and the displayed text ends up lookin ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

AngularJS - A guide on adding a new property to every object within an array

I'm looking to update each item in an array by pushing a scope variable into it. This is my current code: $scope.ProcessExcel = function (data) { //Read the Excel File data. var workbook = XLSX.read(data, { type: 'bin ...

discovering the category for the .click function

After retrieving a list of book objects from a JSON object, I am in the process of displaying them on an HTML page by creating buttons with titles. The goal is to alert the URL of the book when a button is clicked. However, I am facing an issue with access ...

Jquery on method triggers a single event only

I am encountering an issue with adding and removing a class from an element using the on() method to handle click events. The code works fine on the first click, but subsequent clicks do not trigger the event anymore. Here is the code snippet: $(&apo ...

ES5 enables the extension of classes in React

This ES6 syntax works fine for me: import {Component} from 'react'; class A extends Component {} class B extends A { // I can redeclare some methods here } But how would one implement this using ES5? Like so: var React = require('reac ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Error: The function `this.xhr_.upload.addEventListener` is not supported in Firebase Storage

Having some trouble with file uploads. Small files work fine, but when it comes to larger ones I keep getting this error: this.xhr_.upload.addEventListener is not a function. I'm currently using vue.js along with the firebase 6.1.0 npm package. Th ...

Why is my HTTP request callback not being executed?

I've been trying to send an HTTP POST request to a 3rd-party API using a promise method. Oddly enough, the callback function never seems to run, even though when I test the code on its own, the API call is successful. Node.js and the concept of an e ...

Tips for resetting/removing a Chart.js canvas in a React JSX element

I have encountered an issue with chart.js while working on a specific report. Whenever I switch pages to another page that includes chartjs elements and then switch back, the chart displays data labels on the data points like "x: number, y: number". Afte ...

Rearrange Firebase data on the client side

Having trouble sorting data in Firebase for a web project. I tried using orderByChild to filter the data, but now I need to also order it by date. Here's what I've attempted: Tried using object.values with .sort, no luck Attempted to use lodas ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

Nested components knockout knockout knockout! The $(document).ready() function fires off before the nested component is even loaded

I am faced with a situation where I have multiple nested knockout components in my code: <component1> <component2> .... </component2> </component1> The issue here is that while component1 is custom-made by me, component2 ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Using AJAX, retrieve the attribute of a button and assign it to a node

I'm currently facing a dilemma in trying to pass the name of a clicked button to my node server. I have this code snippet in Node.js: app.get('/someUrl', function(req, res) { console.log(req.body.name); }); Meanwhile, my jQuery/ajax ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...