【问题标题】:How to iterate through all properties and its values in Typescript class如何遍历 Typescript 类中的所有属性及其值
【发布时间】:2017-03-18 03:44:09
【问题描述】:

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

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

请帮忙。

【问题讨论】:

标签: typescript object-properties


【解决方案1】:

你不能这样做,如果你看一下编译的代码:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多