javascript - 如何在节点js中定义模型,如对象
问题描述
我的模型如下
var Employee = function (emp) {
(this.firstname = emp.firstName),
(this.middlename = emp.middleName),
(this.lastname = emp.lastName),
(this.mobile_phone = emp.mobilePhone),
(this.home_phone = emp.homePhone),
(this.work_phone = emp.workPhone),
(this.email = emp.email),
(this.personal_email = emp.personalEmail),
(this.password = emp.password),
(this.gender = emp.gender),
(this.address1 = emp.address1),
(this.address2 = emp.address2),
(this.city = emp.city),
(this.state = emp.state);
}
如果我在 Node API 中点击更新请求,那么我会得到如下原始格式数据:
{
"firstName":"Shaunak",
"middleName":"D",
"lastName":"Patel",
"email":"php.shaunak@spaculus.info",
"workPhone":"121212121",
"address":{
"address1":"ewrewrwer",
"address2":"werwe4343434rwer"
}
}
那么如何在我的构造函数模型中定义这种原始格式呢?
解决方案
The OP might have a look into the object destructuring part of Destructuring assignments as well as into Object.assign
.
From the OP's questions one can not really tell what the (final) target structure is supposed to look like. But in case the OP's intention was to achieve both creating a flat property structure from the nested data entries that get passed into the constructor and also taking care of an Employee
object's default values which are not provided by/from the raw data, one might use following parts of JavaScript's Destructuring assignment(s)
- Assigning to new variables names and providing default values
- Setting a function parameter's default value
- Rest in Object Destructuring
function Employee({
gender = null,
password = null,
personalEmail: personal_email = null,
mobilePhone: mobile_phone = null,
workPhone: work_phone = null,
homePhone: home_phone = null,
address: { address1, address2 },
city = null,
state = null,
...baseConfig
}) {
Object.assign(this, baseConfig, {
gender,
password,
personal_email,
mobile_phone,
work_phone,
home_phone,
address1,
address2,
city,
state
});
}
const rawData = {
"firstName":" Shaunak",
"middleName": "D",
"lastName": "Patel",
"email": "php.shaunak@spaculus.info",
"workPhone": "121212121",
"address": {
"address1": "ewrewrwer",
"address2": "werwe4343434rwer",
},
};
console.log(
'... `Employee` instance properties ...',
new Employee(rawData)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
In case the structure of the above logged Employee
instance still does not meet the OP's requirements the OP needs to be more precise about the data passed to the constructor function and the expected structure as well as the default values of an Employee
instance.
推荐阅读
- php - 如何使用 Tagify 从输入中获取 PHP 值
- pandas - 对 DateTimeIndex 进行排序时 Pandas FutureWarning 的解决方法
- javascript - Sinon 存根给出“不是函数”错误
- c++-cli - 作为 String 传入的指针不能位于进程地址空间的底部 64K
- r - 没有 NA 值时显示 NA 条的条形图
- react-native - 在 react-native 中淡出闪屏
- c# - 在两个 ComboBox 之间创建关系
- node.js - 如何在所有路由NodeJS中显示登录用户信息
- python - 从迭代器返回一个浮点数
- spring - 自定义错误页面路由struts 2 + spring boot