4

How do I iterate through list of class properties and get the values of each (only the properties and not the functions)

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

Please help.

Dharshni
  • 181
  • 1
  • 6
  • Possible duplicate of [Iterate through object properties](http://stackoverflow.com/questions/8312459/iterate-through-object-properties) – Igor Mar 17 '17 at 19:42
  • Possible duplicate of [How do I loop through or enumerate a JavaScript object?](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – 4castle Mar 17 '17 at 19:44

2 Answers2

2

You can't do that, if you look at the compiled code of:

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

You'll see that those properties aren't part of it:

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

Only if you assign a value then the property is added:

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

Compiles to:

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

You can use a property decorator for that.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
0

Note: I am making the assumption that you have assigned values to your fields like name. If that is not the case this will not work.

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

or

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

or if you want to loop through the properties see duplicate Iterate through object properties

Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175