Typescript and mapping class

2016-11-11 21:52:37

Class mapping in Typescript

As you may know you can define models in typescript, so how we can map json when initializing class?

 

 

export class User{
public id:number;
public name:string;
public surname:string;
    constructor(data:any){
        var arr = Object.keys(data);
        arr.forEach((val,index)=>{
            if(this.hasOwnProperty(val)){
                this[val] = data[val];
            }
        });
    }
}

var userObj = {
id:1,
name:"Ali",
surname:"Sch"
}

var user = new User(userObj);
console.log(user)

But when code executed its just gives you an empty object!

Just you need to set attributes as undefined Soooooo

export class User{
public id:number = undefined;
public name:string = undefined;
public surname:string = undefined;
    constructor(data:any){
        var arr = Object.keys(data);
        arr.forEach((val,index)=>{
            if(this.hasOwnProperty(val)){
                this[val] = data[val];
            }
        });
    }
}

var userObj = {
id:1,
name:"Ali",
surname:"Sch"
}

var user = new User(userObj);
console.log(user)

Happy Coding!

Tags Cloud

Typescript

mapping

json

data