Reputation: 6289
In doing an ETL to get data from a Sybase database into a MongoDB backend, I can do this:
if (data.hire_date) staffProfile.hireDate = data.hire_date;
This method prevents nulls from being populated into the MongoDB. If data.hire_date
has a value, then it will be dropped into staffProfile.hireDate
. However, if there is no value, it effectively is ignored.
Now, I'd like to create the same result with a ternary expression. Something like:
staffProfile.hireDate = data_hireDate ? data_hireDate : null;
However, I don't want to use null
here, because when I do that I end up with a bunch of nulls in the database. My question really boils down to two things: what is effectively happening in my first example, with the "if" case, when the value is not found? Is the result undefined
? What could I use in the ternary syntax example to effectively write the same conditional check - right through to what is passed when the value doesn't exist?
Would this be the equivalent expression to my first example?
staffProfile.hireDate = data_hireDate ? data_hireDate : undefined;
Upvotes: 1
Views: 47
Reputation: 16384
1. "What is effectively happening in my first example, with the "if" case, when the value is not found? Is the result undefined
?"
Yes, it will be undefined
, if the condition doesn't get passed, and the object property is not created and nothing's assigned to it:
const data = {};
const staffProfile = {};
if (data.hire_date) staffProfile.hireDate = data.hire_date;
console.log("data:", data);
console.log("staffProfile.hireDate:", staffProfile.hireDate);
2. "What could I use in the ternary syntax example to effectively write the same conditional check - right through to what is passed when the value doesn't exist?"
You can achieve absolutely the same result this way:
const data = {};
const staffProfile = {};
data.hire_date ? staffProfile.hireDate = data.hire_date : null;
console.log("data:", data);
console.log("staffProfile.hireDate:", staffProfile.hireDate);
And not this way (it will become null
in this case):
const data = {};
const staffProfile = {};
staffProfile.hireDate = data.hire_date ? data.hire_date : null;
console.log("data:", data);
console.log("staffProfile.hireDate:", staffProfile.hireDate);
Upvotes: 2
Reputation: 725
if date_hireDate
exits, it will be assigned to staffProfile.hireDate. The below syntax is what you want.
staffProfile.hireDate = data_hireDate && data_hireDate
However, it does not make sense. date_hireDate
before &&
operator should be a condition like date_hireDate === something
.
Upvotes: 0