Remove the Falsy values from an Object in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee