Reputation: 131
Based on the initial object Contact
, I have to create a second object. Sometimes the Contact
object will not have certain properties. I wanted to know if there was a way to print value of ConsentDt
using a method within an object.
I know that I could simply code "ConsentDt": Contact.CommPhoneConsentDt
and if that key is not available, ConsentDt
will not be printed in the final output. However, sometimes determining if certain keys should be printed are a little bit more complicated, e.g. only include Email
in the final object if EmailConsentDt == 'Y'
. I also know that I could write functions outside of the object to make these determinations, but I wasn't sure if there was a way to keep the logic all in one object. Thanks in advance!
let Contact = {
"Name": "Kyle Gass",
"CommPhone": "+9-999-999-9999",
"Email": "[email protected]",
"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
Upvotes: 0
Views: 82
Reputation: 141
You can use the get syntax on the object:
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
Upvotes: 1