0

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() }
};
Joshua
  • 95
  • 1
  • 2
  • 11
  • Isn't your example the other way around? You set the value if it is null or undefined. – CoderApprentice Oct 14 '22 at 06:24
  • You could use Optional Chaining `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. – CoderApprentice Oct 14 '22 at 06:28

1 Answers1

0

A very basic example to show you that test var != null answers your problem

let a = null
let b = undefined
let c = "a"

if(a != null) {
  console.log("a")
}
if(b != null) {
  console.log("b")
}
if(c != null) {
  console.log("c")
}
Amaroke
  • 61
  • 8
  • They want to conditionally add properties. – adiga Oct 14 '22 at 06:29
  • 1
    This is actually the correct answer: The short comparison operators `==` and `!=` treat comparisons with `null` test for a value being `null` or `undefined`. For example `null == undefined` is true, but `null == 0` or `null == ""` are both false. – traktor Oct 14 '22 at 06:31
  • 1
    @adiga the question particularly asks about "...when a value is not null and is not undefined?" – traktor Oct 14 '22 at 06:34
  • @traktor I'm well aware of that. The question is about how to add a property conditionally and there is no property being added. – adiga Oct 14 '22 at 06:36
  • Also, it is better to be explicit about `!== null` and `typeof x !== "undefined"`. The `null == undefined` is not very well known and when someone looks at the code it is immediately not apparent that they are checking both for null and undefined. – adiga Oct 14 '22 at 06:38