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

JavascriptArraysTypescriptEnumsElement

Javascript Problem Overview


What is the proper way to loop through literals of an enum in TypeScript?

(I am currently using TypeScript 1.8.1.)

I've got the following enum:

export enum MotifIntervention {
    Intrusion,
    Identification,
    AbsenceTest,
    Autre
}

export class InterventionDetails implements OnInit
{
    constructor(private interService: InterventionService)
    {
        let i:number = 0;
        for (let motif in MotifIntervention) {
            console.log(motif);
        }
    }

The result displayed is a list

0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre

I do want only four iterations in the loop as there are only four elements in the enum. I don't want to have 0 1 2 and 3 that seem to be index numbers of the enum.

Javascript Solutions


Solution 1 - Javascript

Two options:

for (let item in MotifIntervention) {
	if (isNaN(Number(item))) {
		console.log(item);
	}
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
	A = "a",
	B = "b",
	C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
	A: "a",
	B: "b",
	C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthony BrenelièreView Question on Stackoverflow
Solution 1 - JavascriptNitzan TomerView Answer on Stackoverflow