Remove Null Values from an Object in Javascript

avatar

Borislav Hadzhiev

Thu Oct 14 20211 min read

banner

Photo by Jessica Polar

Remove Null Values from an Object #

To remove all null values from an object:

  1. Call the Object.keys() method to get an array of the object's keys.
  2. Call the forEach() method to iterate over the array and delete all null values using the delete operator.
index.js
const obj = { one: null, two: 2, three: null, }; Object.keys(obj).forEach(key => { if (obj[key] === null) { delete obj[key]; } }); console.log(obj); // ๐Ÿ‘‰๏ธ {two: 2}

The Object.keys method returns an array containing the object's keys.

index.js
const obj = { one: null, two: 2, three: null, }; // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] console.log(Object.keys(obj));

The Array.forEach method allows us to iterate over the array of keys.

We check if the value, associated to the current key is equal to null and if the condition is met, we use the delete operator to delete the key-value pair.

The forEach method is not supported in Internet Explorer. If you have to support the browser, use the next approach covered in this article.

To remove all null values from an object:

  1. Use the for...in loop to iterate over the object.
  2. On each iteration, check if the value is equal to null and delete the value if it satisfies the condition.
index.js
// Supported in IE const obj = { one: null, two: 2, three: null, }; for (const key in obj) { if (obj[key] === null) { delete obj[key]; } } console.log(obj); // ๐Ÿ‘‰๏ธ {two: 2}

The for...in loop allows us to iterate over the object's properties.

We check if the value of the current property is equal to null and if either condition is satisfied, we delete the key-value pair.

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