Sometimes we get data from a database that has one or more than one value that is undefined, null, or empty.
Then we further use those values somewhere in our app but without falsy properties.
In my case, I was implementing the firebase analytics function to the app, which accepts an object, but in case of undefined property it gives me an error, So I have to remove undefined properties from object, there might be many use cases.
Example of Falsy Values in Javascript Object
Let's say we have a user object in the database. Some users provide their phone and address while signup and some don’t prefer it.
I prefer using javascript Object.assign() method to eliminate falsy values.
Object.assign() method can be used for cloning and merging objects.
The first parameter of Object.assign() method is target, and rest of the parameters are sources, in our case, we don’t have any target so we made it an empty object, for the rest of the values (source) we use short circuit && operator, it means only add those values that are truthy.
Removing falsy values from a JavaScript object with TypeScript: Solution
interface User {nick: stringemail: stringphone?: stringaddress?: string}const user: User = {nick: 'John',phone: undefined,address: '',}const { nick, email, phone, address } = userconst userInfo: User = Object.assign({},nick && { nick },email && { email },phone && { phone },address && { address })console.log('userInfo ->', userInfo)// userInfo -> {nick: 'John', email: '[email protected]'}
I hope you found this article informative and learned something new today.

