0

I have an enum file where I have defined an object for PaymentTypes:

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

Now, when I receive data as an array from my database I also receive the PaymentType as a number:

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

Now my question is, how can I filter out each payment type in the array and convert the number to the string that's defined in the enum file so that I can us this data to display it to the user in the front end?

So that I have something like this that I can work with:

orderFiltered:
        [
            { "id": 0, "name": "Available", "PaymentType": "Invoice" },
            { "id": 1, "name": "Ready", "PaymentType": "PrePayment" },
            { "id": 2, "name": "Started", "PaymentType": "CreditCard" }
        ];
bobdolan
  • 563
  • 3
  • 9
  • 21

1 Answers1

1

You can use map to create a new array of objects that contains the original data and the name of the enum member, which you can get using 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);

One thing to note though is that using the enum member name as a display might not be the friendliest of use experiences.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357