George Edwards George Edwards - 1 month ago 10
TypeScript Question

Enumerate properties on TypeScript Object

Given the following class, how can I enumerate it's properties, i.e. get an output like

[station1, station2, station3 ...]
. I can only see how to enumerate the values of the properties, i.e.
[null, null, null]
.

class stationGuide {
station1: any;
station2: any;
station3: any;

constructor(){
this.station1 = null;
this.station2 = null;
this.station3 = null;
}
}

Answer

You have two options, using the Object.keys() and then forEach, or use for/in:

class stationGuide {
    station1: any;
    station2: any;
    station3: any;

    constructor(){
        this.station1 = null;
        this.station2 = null;
        this.station3 = null;
     }
}

let a = new stationGuide();
Object.keys(a).forEach(key => console.log(key));

for (let key in a) {
    console.log(key);
}

(code in playground)

Comments