Changing Enum Value to Text

In my enum file, I have defined an object for PaymentTypes:

export enum PaymentTypes {
   Invoice = 1,
   CreditCard = 2,
   PrePayment = 3,
}

When I fetch data as an array from the database, it also includes PaymentType represented as numbers:

 order:
    [
        { "id": 0, "name": "Available", "PaymentType": 1 },
        { "id": 1, "name": "Ready", "PaymentType": 3 },
        { "id": 2, "name": "Started", "PaymentType": 2 }
    ];

My query now is, how can I filter each payment type in the array and covert the number to the string defined in the enum file? This way, I can use this data to show to the user on the front end.

I need to transform the data to something like this:

orderFiltered:
        [
            { "id": 0, "name": "Available", "PaymentType": "Invoice" },
            { "id": 1, "name": "Ready", "PaymentType": "PrePayment" },
            { "id": 2, "name": "Started", "PaymentType": "CreditCard" }
        ];

Answer №1

Utilize the map method to generate a fresh array of objects containing both the initial data and the label of the enum member, retrievable through PaymentTypes[PaymentType]

let order = [
    { "id": 0, "name": "Available", "PaymentType": 1 },
    { "id": 1, "name": "Ready", "PaymentType": 3 },
    { "id": 2, "name": "Started", "PaymentType": 2 }
];

enum PaymentTypes {
   Invoice = 1,
   CreditCard = 2,
   PrePayment = 3,
}
let orderFiltered = order.map(o => Object.assign({}, o, { PaymentTypeDisplayName: PaymentTypes[o.PaymentType] }));
console.log(orderFiltered);

It's important to consider that using the enum member name for display purposes may not offer the most user-friendly experience.

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

Reasons for dividing by 1 in JavaScript

While completing a basic programming assignment from my teacher, I encountered an interesting issue in Javascript. I found that when dividing a number by 1, it returns an unexpected value. Can anyone provide an explanation for this? I have created a jsfidd ...

Dealing with the issue of incompatible types in TypeScript with Vue 3 and Vuetify: How to handle numbers that are not assignable to type Readonly<any

Currently, I am utilizing Vite 3 along with Vue 3 and Vuetify 3 (including the Volar extension and ESLint). Additionally, I am incorporating the composition API in script setup mode. Within my HTML code, I am utilizing Vuetify's v-select. Unfortunate ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

I'm running into a "timeout" issue with socket.io and a self-signed SSL connection. Can anyone help me troubleshoot this?

After setting up a nodejs server with HTTPS, everything seems to be working fine when sending GET requests. However, I encountered an error message 'WebSocket was closed before the connection was established' when trying to connect another nodejs ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...

What could be causing express to have trouble finding the ejs file in the views directory?

Recently delved into the world of learning NodeJS and Express. // Working with express framework var express = require("express"); var app = express(); app.get("/", (req,res) => { res.render("home.ejs"); }) //Setting up port listening app.listen ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...

What is the most effective method for establishing functions in AngularJS?

Hey there, I'm currently working on a function in AngularJS and I'm not sure what the best practice is for defining methods. Any suggestions would be greatly appreciated. Option 1: var getBranchKey = function(currentBranchName) { }; Option 2: ...

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

Pass the ID of the <a> element from one function to another

I am a beginner in javascript/jQuery, so please be patient with me if my question seems too simple for you and too challenging for me. I have a function that I won't post the entire code for because it would make this too lengthy. Another function ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

Completely triggering a forced refresh on a single page application, disregarding cache, service workers, and all other

After experimenting with service workers on my Vue-built website, I made a critical error that has left Safari on my iPhone displaying only a blank page. To troubleshoot the issue, I connected my phone to my Mac and utilized Safari's inspector tool t ...

What is the process for integrating Internet Explorer 10 compatibility into a basic VueJs component?

I am facing an issue with a VueJs component that is not rendering in IE 10. Context: The Vue component I am working on is a company events list with basic filtering and sorting functionalities. Unfortunately, IE10 support is required for this project. Eve ...

What steps should be taken in order to resolve the error message "Type is missing an index signature"?

Is there a solution to this type error? The argument of type 'Query' is causing an issue as it cannot be assigned to the parameter of type 'Input'. This is due to the absence of an index signature in type 'Query'.(2345) In ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

Saving and retrieving user input as a variable using Javascript and HTML local storage

This is the foundation of my HTML page. When the "remember text" paragraph is clicked, the data in the input text box is saved to local storage as a string. Clicking the "recall text" paragraph loads the stored data into the "recalled text" paragraph. I am ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...