首页 > 解决方案 > 对象方法可以用来创建对象吗?

问题描述

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

我知道我可以简单地编码"ConsentDt": Contact.CommPhoneConsentDt,如果该密钥不可用,ConsentDt则不会在最终输出中打印。但是,有时确定是否应该打印某些键有点复杂,例如只包含Email在最终对象中 if EmailConsentDt == 'Y'。我也知道我可以在对象之外编写函数来做出这些决定,但我不确定是否有办法将逻辑全部保存在一个对象中。提前致谢!

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 

标签: javascriptobjectmethods

解决方案


您可以在对象上使用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 


推荐阅读