Enumerate properties on an object
Given the following class, how can I enumerate its 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;
}
}
Solution 1:
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)
Solution 2:
With the Reflect object you are able to to access and modify any object programmatically. This approach also doesn't throw a "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'" error.
class Cat {
name: string
age: number
constructor(name: string, age: number){
this.name = name
this.age = age
}
}
function printObject(obj: any):void{
const keys = Object.keys(obj)
const values = keys.map(key => `${key}: ${Reflect.get(obj,key)}`)
console.log(values)
}
const cat = new Cat("Fluffy", 5)
const dog = {
name: "Charlie",
age: 12,
weight: 20
}
printObject(cat)
printObject(dog)
(code in playground)