Enumerate object properties

Given the following class, how can I list its properties, that is, get output such as [station1, station2, station3...] ?

I can only see how to list property values, i.e. [null, null, null] .

 class stationGuide { station1: any; station2: any; station3: any; constructor(){ this.station1 = null; this.station2 = null; this.station3 = null; } } 
+42
source share
2 answers

You have two options using 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 on the playground )

+73
source

With the Reflect object, you can access any object and change it programmatically. This approach also fails "The element is implicitly of the type" any "because an expression of the type" string "cannot be used to index errors of the type" {} "".

 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 on the playground )

0
source

Source: https://habr.com/ru/post/1011621/


All Articles