Remove Falsy Values from Javascript Object with Object.assign() method

2 min read

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

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.

Solution

const user = {
nick: 'John',
email: 'john@email.com',
phone: undefined,
address: '',
}
const { nick, email, phone, address } = user
const userInfo = Object.assign(
{},
nick && { nick },
email && { email },
phone && { phone },
address && { address }
)
console.log('userInfo ->', userInfo)
// userInfo -> {nick: 'John', email: 'john@email.com'}