I have the following method which takes a set of data and creates a new instance of a model from it. The reportTemplateData
comes in as an object which I destructure in order to pass in as a list of properties to the class constructor.
Whilst this works, I feel like it could be done far more efficiently. Is there a more elegant way to do this in a line or so?
addReportTemplate(reportTemplateData) {
const {
id,
pageId,
profileTemplateId,
userId,
name,
description,
createdAt,
updatedAt,
deletedAt,
createdBy,
updatedBy,
deletedBy,
reportTemplateColumns,
} = reportTemplateData;
const newReportTemplate = new ReportTemplate(
id,
pageId,
profileTemplateId,
userId,
name,
description,
createdAt,
updatedAt,
deletedAt,
createdBy,
updatedBy,
deletedBy,
reportTemplateColumns,
);
this.reportTemplates.push(reportTemplates);
}
EDIT
Worth noting that if you go for the const newReportTemplate = new ReportTemplate({...reportTemplateData})
solution, you must match your data properties precisely to your class constructor parameters. This was an issue for me where the data was coming in in snake_case whereas my Javascript model was looking for camelCase.
Assuming that only the properties you want to pass are in that object.
addReportTemplate(reportTemplateData) {
const newReportTemplate = new ReportTemplate({ ...reportTemplateData });
this.reportTemplates.push(reportTemplates);
}
If there are a few properties you want to exclude, destructure them.
addReportTemplate(reportTemplateData) {
const {
excluded1,
excluded2,
...properties,
} = reportTemplateData;
const newReportTemplate = new ReportTemplate({ ...properties });
this.reportTemplates.push(reportTemplates);
}
Both of these approaches require a change in ReportTemplate class where the constructor takes an object as parameter. See two examples of how this approach would work in this pen.