首页 > 解决方案 > 如何在节点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"
     }
    }

那么如何在我的构造函数模型中定义这种原始格式呢?

标签: javascriptnode.js

解决方案


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)

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.


推荐阅读