如何在 Typescript class 中遍历所有属性及其值

How to iterate through all properties and its values in Typescript class

如何遍历 class 属性列表并获取每个属性的值(仅属性而非函数)

class Person{
 name:string;
 age:number;
 address:Address;
 getObjectProperties(){
   let json = {};
    // I need to get the name, age and address in this JSON and return it
    // how to do this dynamically, rather than getting one by one 
    // like json["name"] = this.name;
   return json;
 }
}

请帮忙。

你不能那样做,如果你看看编译后的代码:

class Person {
    name: string;
    age: number;
    address: Address;
}

您会发现这些属性不在其中:

var Person = (function () {
    function Person() {
    }
    return Person;
}());

仅当您分配一个值时才会添加 属性:

class Person {
    name: string = "name";
}

编译为:

var Person = (function () {
    function Person() {
        this.name = "name";
    }
    return Person;
}());

您可以为此使用 property decorator

注意:我假设您已经为 name 等字段分配了值。如果不是这种情况,这将不起作用。

// if you want json as a string
getObjectProperties(){
   let json = JSON.stringify(this);
}

// if you want a copy of the fields and their values
getObjectProperties(){
   let json = JSON.parse(JSON.stringify(this));
}

或者,如果您想遍历属性,请参阅副本 Iterate through object properties