Different ways to showcase the name values of a numerical enum

I am currently in the process of developing a small vue.js web application tool designed for viewing and editing a backend config file formatted as JSON. Within this object, there is an enum field represented on the backend as a uint. My goal is to find a way to map the display name to the numerical value in the JSON and then present these options in a dropdown select menu. At the moment, I have a v-for element that iterates through each config record, displaying each field.

The structure of the object is as follows:

{records:[
  {
    id:"12345",
    target:678,
    src:"path/to/src"
    operator:0 // backend enum where values 0,1,2... correspond to specific operators
  },
  ... // more records
}

This is what I currently have for the dropdown selection:

<label class="recorditem">Comparison Operator:
  <select v-model="record.operator">
    <option>EQ</option>   // should map to 0
    <option>NEQ</option>  // should map to 1
    <option>GT</option>   // should map to 2
    <option>GTE</option>  // should map to 3
    <option>LT</option>   // should map to 4
    <option>LTE</option>  // should map to 5
  </select>
</label>

I am seeking a method to automatically convert the numerical value in the JSON to display text such as "EQ", "NEQ", etc. within the dropdown menu using JavaScript and Vue. Additionally, when the user selects an option from the dropdown menu, I want it to update the data with the corresponding numerical value defined by the backend, rather than the displayed text.

EDIT: I removed a section of code explaining how the backend generates the JSON and why it's structured as an enum. Unfortunately, this caused the question to be flagged as a duplicate, so I have eliminated that portion.

Answer №1

An enumeration should be defined within the application to facilitate the mapping of keys to values. The TypeScript `enum` syntax allows for a convenient two-way mapping system. In JavaScript, this can simply be achieved using a plain object, which may necessitate converting between string and numeric `operator` values. Alternatively, an array can be used for zero-based consecutive keys, or a map for more flexibility despite sacrificing some elegance in syntax:

const operatorsMap = new Map([
  [0, 'EQ'],
  ...
]);

This `operatorsMap` is then imported into a component and made accessible to a template for easy usage:

<option v-for="[key, name] in operatorsMap" :key="key" :value="key">{{name}}</option> 

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

Issue with VueJS computed property failing to update when using a boolean prop

I'm facing an issue with a Vue (2.6.11 via Nuxt) component that receives a Boolean property from its parent and uses it to calculate additional computed properties. Everything displays correctly after the initial rendering. However, when the parent to ...

Object containing properties for serializing to JSON format

I'm dealing with a class that has some internal properties and I want to convert them into json format. How can I achieve this? For example: public class Foo { internal int num1 { get; set; } internal double num2 { get; set; } public str ...

Encountering an ASyncTask HTTP issue

I seem to be having an issue with my PHP code where I'm not getting the expected output "badminton society" from this specific piece of code: print(json_encode($row['Description'])); If anyone can help me pinpoint the mistake, that would b ...

Struggling with retrieving data from a JSON file within a Flutter Stateful Widget?

I encountered an issue while loading data from a JSON file. I suspect the problem lies in fetching the data. Any insights on what might be causing this? Although I am not an expert Flutter developer, it's more of a hobby for me so please bear with me ...

Angular allows developers to easily show or hide different elements on a webpage

I have a situation where I need to display date and time within two separate div elements. There are two checkboxes available: 1. Add Additional: This will add one more div for each date and time. 2. Time/Date will be the same: This will add just the date ...

using selenium to interact with elements within the window object

I'm a newcomer to selenium and javascript and looking to incorporate the VisualEvent javascript into pages opened in a selenium-controlled browser. My goal is to access its variables from selenium in java. I've successfully completed the first ph ...

Load all images in the directory and its nested directories beforehand

I have a vast image gallery containing hundreds of images, sixty per page. I want all these images to start pre-loading as soon as any page on the site finishes loading since the gallery is a crucial destination for almost every visitor. Currently, I have ...

I'm encountering some challenges with my functions in ReactJS when it comes to updating state and working with promises

Currently, I am handling form field validation by running regex checks and updating the state to 'success' or 'error' accordingly (utilizing react-bootstrap). I have a total of 6 functions that require execution, but the validation fun ...

Whenever I clear the contents of the datatable, I notice that 2 thead elements

I am facing an issue with a table that I populate using jQuery's .append() function and then initialize it as a datatable. Since the data is not fetched via an ajax call, I clear both the tbody and thead using .empty(). However, I encounter a problem ...

pdfmake: Stabilized Vertical Column Dimensions

I'm working on a project where I need to add text to a column with a fixed height and width. So far, I've successfully implemented a fixed width, but I'm struggling with setting a fixed height for the column. Below is the code I've bee ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

Linking information within a three-dimensional mesh structure in the context of a city created through procedural generation

Currently, I am working on developing a procedurally generated city using three.js, focusing mainly on creating buildings. One of the crucial requirements for this project is that when a user clicks on a building with their mouse, detailed information abou ...

Limit the random color generator function to only produce a predetermined color in JavaScript

By utilizing the following function, I am able to create random colors: function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++) { color += le ...

Unable to install local dependency using npm

After successfully using npm install react-financial-charts, I decided to include the package locally for specific reasons. I checked out the master branch of react-financial-charts from Github, resulting in two folders: C:\Users\user\projec ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

What are the best ways to ensure a smooth patching process for a django

In my Django project named project, I attempted to patch the jsonfield within the project/__init__.py file: import json import jsonfield def get_prep_value(self, value): if value is None: if not se ...

Is there a way to transform JSON-Patch into the MarkLogic JSON patch format?

Comparing the JSON patch specification used in MarkLogic's PATCH API to the standard JSON-Path (RFC 6902), it shows remarkable similarities, but there are differences as well. For instance, when adding a node to a document like this: { "parent& ...

Experiencing the 'invalid_form_data' error while attempting to upload a file to the Slack API via the files.upload method in Angular 8

I am currently working on a project that involves collecting form data, including a file upload. I am trying to implement a feature where the uploaded file is automatically sent to a Slack channel upon submission of the form. Despite following the guidance ...

Using Yii to work with a nested JSON array in PHP

Looking to enhance my code: /*foreach($result as $value) { $model_name=ResRegistration::model()->findByAttributes(array('id'=>$value->user_id)); $model_image=ResImages::model()->findByAttributes(array(&a ...

Encountering difficulties when trying to send requests to an API through AJAX

Our company relies on the software nocrm.io for managing leads and customers. I am looking to integrate their API into our web application to streamline information exchange through GET and POST requests. However, I am facing challenges while trying to mak ...