0

Having typescript code presented below, which creates new record in the Firestore database, is it possible to omit (by writing one line of inline code) one of the key-value pair if the value equals null?

firestore.doc(`users/${user.uid}`).set({
   email: user.email,
   name: user.displayName,
   phone: user.phoneNumber, // (user.phoneNumber ? phone: user.phoneNumber), ... ?
   createdAt: firebase.firestore.FieldValue.serverTimestamp(),
});
Eric
  • 1,685
  • 1
  • 17
  • 32

1 Answers1

1

You can use the object destruction with ternary expression to do it:

firestore.doc(`users/${user.uid}`).set({
   email: user.email,
   name: user.displayName,
   ...(user.phoneNumber ? { phone: user.phoneNumber } : undefined),
   createdAt: firebase.firestore.FieldValue.serverTimestamp(),
});

It's not very elegant, but it get its job done in one line:

const phone = null;

const obj = {
  name: 'Alice',
  age: 24,
  ...(phone ? { phone } : undefined),
};

console.log(obj);

Edit

According to this answer that ford04 mentioned, it also can be shortened like this:

 ...(user.phoneNumber && { phone: user.phoneNumber }),

Edit, again

But it's better to check its type properly that it might cause 0 and "" are not stored correctly

 ...(![undefined, null].includes(user.phoneNumber) && { phone: user.phoneNumber })
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • This solution seems to work fine as the record in the database is created as intended. I'm just wondering is there more elegant syntax approach to this problem? Thanks for pointing the answer out – Eric Dec 03 '20 at 09:33