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() }
};
2
  • Isn't your example the other way around? You set the value if it is null or undefined. Commented Oct 14, 2022 at 6: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. Commented Oct 14, 2022 at 6:28

1 Answer 1

-1

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")
}

Sign up to request clarification or add additional context in comments.

5 Comments

They want to conditionally add properties.
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.
@adiga the question particularly asks about "...when a value is not null and is not undefined?"
@traktor I'm well aware of that. The question is about how to add a property conditionally and there is no property being added.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.