Reputation: 4293
I have an typeorm
entity of the following form:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
isActive: boolean;
}
Now I am looking to get the instance fields from this entity class into an array, like below:
['id', 'firstName', 'lastName', 'isActive']
How can I achieve that?
I tried the following but with no help:
class Me extends User{
constructor() {
super()
}
}
const me = new Me()
console.log(Object.keys(me)) // []
Upvotes: 1
Views: 2274
Reputation: 2531
You might be able to do something like this:
const userProps = getConnection()
.getMetadata(User)
.ownColumns
.map(column => column.propertyName);
This means that you obtain metadata from an entity if you take the class function (AKA constructor) and use the .getMetadata
method on the DB connection.
Reference:
Get all properties from a entity #1764
Upvotes: 1
Reputation: 7
Give initial values in your User class to the properties. They are null now, Object.keys wont list them. Try this:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number = 0;
@Column()
firstName: string = "";
@Column()
lastName: string = "";
@Column()
isActive: boolean = false;
}
Alternative solution is when you fill the attrs manually:
const user = new User();
user.id = 0;
user.firstName = "";
user.lastName = "";
user.isActive = false;
Upvotes: 0