Rapid UI Development in Just 3 Days!

Starting at $100 for the first milestone of UI Development

Ensuring that your codebase is scalable, well-organized, and reusable

Integrate backend-as-a-service platforms like Appwrite and Supabase

Reusable components, custom hooks, services, and other React best practices

Consistent Code using ESLint and Prettier

Choose your stack: React.js, Next.js, Gatsby.js

Book A Free Call Now!
remove falsy values from js object with object assign

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 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: string
email: string
phone?: string
address?: string
}
const user: User = {
nick: 'John',
phone: undefined,
address: '',
}
const { nick, email, phone, address } = user
const 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.