可以使用对象方法创建对象



基于初始对象Contact,我必须创建第二个对象。有时Contact对象将没有某些属性。我想知道是否有一种使用对象中的方法打印ConsentDt值的方法。

我知道我可以简单地代码"ConsentDt": Contact.CommPhoneConsentDt,如果该密钥不可用,则ConsentDt不会在最终输出中打印。但是,有时确定是否应该打印某些键更为复杂,例如如果EmailConsentDt == 'Y',则仅在最终对象中包括Email。我还知道我可以在对象之外编写功能以做出这些确定,但是我不确定是否有一种将逻辑全部保留在一个对象中的方法。预先感谢!

let Contact = {
  "Name": "Kyle Gass",
  "CommPhone": "+9-999-999-9999",
  "Email": "tenacious@d.org",
  "CommPhoneConsentCd": "Y",
  "CommPhoneConsentDt": "2019/8/1",
  "EmailConsentCd": "N"
}
let Communications = {
  "PhoneInfo" : {
    "PhoneTypeCd": "Cell",
    "PhoneNumber": Contact.CommPhone,
    "PhoneNumberValidInd": "N",
    "ContactPreferenceType": "Primary",
    "ConsentCd": Contact.CommPhoneConsentCd,
    "ConsentDt": function(Contact) {
      if (Contact.hasOwnProperty("CommPhoneConsentDt")) {
        return Contact.CommPhoneConsentDt
      } else {
        return
      }
    }  
  }
}
console.log(Communications.PhoneInfo.ConsentDt);
//I want ConsentDt of 2019/8/1 to print out 

您可以在对象上使用get语法:

Communications = {
  "PhoneInfo" : {
    "PhoneTypeCd": "Cell",
    "PhoneNumber": Contact.CommPhone,
    "PhoneNumberValidInd": "N",
    "ContactPreferenceType": "Primary",
    "ConsentCd": Contact.CommPhoneConsentCd,
    get "ConsentDt"() {
      if (Contact.hasOwnProperty("CommPhoneConsentDt")) {
        return Contact.CommPhoneConsentDt
      } else {
        return
      }
    }  
  }
}
console.log(Communications.PhoneInfo.ConsentDt);
ConsentDt of 2019/8/1 is printed out 

最新更新