Reputation:
I have an Class Car
with some properties:
public id: number;
public roleId: number;
public roleName: string;
Also I have the same object {id: 1, roleId: 1, roleName: 4}
How to assign this object to each property?
I dont want to use:
this.id = obj.id;
this.roleName = obj.roleName;
this.roleId = obj.roleId;
Upvotes: 1
Views: 1286
Reputation: 28708
Try this syntax:
class Car {
public id?: number;
public roleId?: number;
public roleName?: string;
constructor(values: Car) {
Object.assign(this, values);
}
}
and use it:
let car = new Car({id: 1, roleId: 1, roleName: "4"});
Upvotes: 1
Reputation: 2133
Use object.assign property.
Object.assign(new Car(), {
id: obj.id,
roleName : obj.roleName,
roleId : obj.roleId
})
Upvotes: 2