Explain Codes LogoExplain Codes Logo

How can I loop through enum values for display in radio buttons?

javascript
enum
javascript-enum
radio-buttons
Anton ShumikhinbyAnton Shumikhin·Jan 11, 2025
TLDR
// We have a beautiful 'Colors' enum const Colors = { RED: 'Red', GREEN: 'Green', BLUE: 'Blue' }; // Sit back and let the magic unfold const radios = Object.entries(Colors).map(([key, value]) => `<label><input type="radio" name="color" value="${key}">${value}</label>` ).join(''); // Voila! 'radios' is now an HTML string for our radio buttons

Enum types and iteration considerations

In the enchanting world of TypeScript enums, two main creatures roam the plains – numeric enums and string enums. Please proceed with caution, as these creatures behave differently after the transmutation to JavaScript.

Numeric enum iteration

// Meet our enum friends Apple, Orange, and Banana enum Fruits { Apple, Orange, Banana } for (const fruitKey in Fruits) { if (!isNaN(Number(fruitKey))) continue; // Not the number we're looking for (It's not the Jedi way!) const radioButton = `<label><input type="radio" name="fruit" value="${Fruits[fruitKey]}">${fruitKey}</label>`; } // Don't forget to close the refrigerator!

String enum iteration

// It's all about Colors! enum Colors { RED = 'Red', GREEN = 'Green', BLUE = 'Blue' } // For each color in our rainbow... Object.keys(Colors).forEach(color => { const radioButton = `<label><input type="radio" name="color" value="${color}"> ${Colors[color]}</label>`; }) // And the world was colored!

Advanced techniques for enum iteration

You can wield JavaScript's almighty Object.keys() and Object.values() like magic wands. However, there might be situations you want to summon filter() or map() for more precise manipulation.

Filtering and mapping in enum iteration (not a GPS!)

// Enum definition enum Status { PENDING, PROCESSING, COMPLETED } // We conjure radio buttons, skipping unnecessary numeric keys const statusRadios = Object.keys(Status) .filter(key => isNaN(Number(key))) // This is not the key you're looking for! .map(key => `<label><input type="radio" name="status" value="${key}">${Status[key]}</label>`) .join('');

Reverse mapping in enum iteration

Powerful TypeScript sorcery has laid a curse upon numeric enums - reverse mapping. Be smart and avoid trouble by filtering out numeric string keys.

const enumButtons = Object.entries(Status) .filter(([key]) => isNaN(Number(key))) // "I have the high ground" - keys .map(([key, value]) => `<label><input type="radio" name="status" value="${value}">${key}</label>`) .join('');

Armour up for TypeScript enums

In TypeScript, always check your version compatibility and be mindful about config settings and runtime environments. Ready your lightsaber, young padawan!