Enumerate properties on an object

TypescriptIterator

Typescript Problem Overview


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;
     }
}

Typescript Solutions


Solution 1 - Typescript

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 - Typescript

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)

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
QuestionGeorge EdwardsView Question on Stackoverflow
Solution 1 - TypescriptNitzan TomerView Answer on Stackoverflow
Solution 2 - TypescriptszuuukenView Answer on Stackoverflow