I struggled find a way to get my enum variable name and the string part for the display name (to use both the variable name and string 'display' name)
I wanted this because I would use the variable name in my filter queries, and the display name to show on the front end.
So I found a way to create an object to act as an enum, and thought id just add it here for you guys.
So Instead of creating an enum, just create an object in this format.
export const RewardCategory = {
swapPoints: {variable: 'swapPoints', display: 'Swap Points' },
charity: {variable: 'charity', display: 'Charity' },
discountVouchers: {variable: 'discountVouchers', display: 'Discount Vouchers' }
}
Then, simply use it like this.
RewardCategory.swapPoints.display
or
RewardCategory.swapPoints.variable
Instead of creating an Interface or an Enum you can use a class with private constructor. And create static readonly
instances of your class.
export class RewardCategory {
public static readonly swapPoints = new RewardCategory('swapPoints', 'Swap Points');
public static readonly charity = new RewardCategory('charity', 'Charity');
public static readonly discountVouchers = new RewardCategory('discountVouchers', 'Discount Vouchers');
private constructor(public readonly variable: string, public readonly displayName: string) {
}
}
Then you could use it like this:
RewardCategory.charity.displayName
or
RewardCategory.charity.variable
Enums are encoded as plain javascript objects so you can do the following:
enum Numbers {
one = 'number one',
two = 'the second number'
}
for (const key in Numbers)
console.log(`key: ${key}, value: ${Numbers[key]}`);
function getTheKeyFromTheValue(value: string) {
for (const key in Numbers)
if (Numbers[key] === value)
return key;
return undefined; // Couldn't find it
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With