Remove the Falsy values from an Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 13, 2021

banner

Photo from Unsplash

Remove the Falsy values from an Object #

To remove the falsy values from an object, pass the object to the Object.keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete each falsy value from the object.

index.js
const obj = { first: undefined, second: null, third: 'hello', }; Object.keys(obj).forEach(key => { if (!obj[key]) { delete obj[key]; } }); // 👇️ {third: 'hello'} console.log(obj);

The first step is to use the Object.keys method to get an array of the object's keys.

index.js
const obj = { first: undefined, second: null, third: 'hello', }; // 👇️ ['first', 'second', 'third'] console.log(Object.keys(obj));

We can iterate over the array of keys using the Array.forEach method.

The function we passed to the forEach method gets called with each element in the array.

On each iteration, we check if the current value is falsy using the logical NOT (!) operator.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

If the condition is met, we use the delete keyword to remove the key-value pair from the object.

This approach changes the object in place. Alternatively you can create a new object and not mutate the original one.

To remove the falsy values from an object, pass the object to the Object.keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and add all truthy values to a new object.

index.js
const obj = { first: undefined, second: null, third: 'hello', }; const newObj = {}; Object.keys(obj).forEach(key => { if (obj[key]) { newObj[key] = obj[key]; } }); console.log(newObj); // 👉️ {third: 'hello'}

This approach is very similar to the last example, however instead of deleting the falsy values from the object, we add all of the object's truthy values to a new object.

This should be your preferred approach when you don't want to mutate the original object.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.