如何遍历Typescript类中的所有属性及其值

时间:2017-03-17 19:38:56

标签: typescript object-properties

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

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

请帮忙。

2 个答案:

答案 0 :(得分:2)

如果您查看以下编译代码,则无法执行此操作:

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

答案 1 :(得分:0)

注意:我假设您已为// 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));
}

{{1}}

或者如果要遍历属性,请参阅重复Iterate through object properties

相关问题