What's the best way to set a variable in a JSON array only when a value is not null and is not undefined?
Example code is:
var test = {
"email": object.email.toString(),
"phone": object.phone.toString()
};
I want the email variable to only be passed if object.email is defined and the phone number variable as well if object.phone is defined. Effectively, the logic would be something like:
var test = {
if (object.email === null || typeof object.email === 'undefined') { "email": object.email.toString(), }
if (object.phone === null || typeof object.phone === 'undefined') { "phone": object.phone.toString() }
};
object.email?.toString(), but then the key in the JSON array would always be set, and its value would be undefined if email is undefined. If you don't want the key in the JSON array in that case, using if-statements is still the way to go.