javascript - 对象方法可以用来创建对象吗?
问题描述
基于初始对象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
解决方案
您可以在对象上使用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
推荐阅读
- winforms - 如何从 UserControl 更改控件属性
- java - 如何强制 Java 应用程序应该使用哪个类文件?
- vue.js - Vue根据对象值分配样式
- python - 使用 Python 3.8 生成“减 x 天”的语法?
- php - 解密由 MCRYPT_RIJNDAEL_128 加密的字符串
- python-3.x - 在基于组的 pandas DataFrame 中将单元格向左移动
- javascript - 如何使用 JAVASCRIPT 删除文本行
- python - python“zip”和for循环创建一个对象
- python - 有没有办法用python控制连接到主板中12v rgb接头的rgb条?
- scilab - 在scilab中求解常微分方程的问题