// We have a beautiful 'Colors' enum const Colors = { RED: 'Red', GREEN: 'Green', BLUE: 'Blue' };
// Sit back and let the magic unfoldconst 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 Bananaenum 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 definitionenum Status { PENDING, PROCESSING, COMPLETED }
// We conjure radio buttons, skipping unnecessary numeric keysconst 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!