Remove Null and Undefined Values from Object in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

Remove Null and Undefined Values from Object #

To remove all null and undefined values from an object:

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

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

index.js
const obj = { a: null, b: undefined, c: 'test', }; // ๐Ÿ‘‡๏ธ ['a', 'b', 'c'] console.log(Object.keys(obj))

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

We check if the value of the current key is null or undefined and if either condition is met, we use the delete operator to delete the key-value pair.

Notice that we use the || (or) operator, this means that only one of the conditions has to return true for the if block to run.

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 and undefined 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 or undefined and delete the value if it matches either condition.
index.js
// Supported in IE const obj = { a: null, b: undefined, c: 'test', }; for (const key in obj) { if (obj[key] === null || obj[key] === undefined) { delete obj[key]; } } console.log(obj); // ๐Ÿ‘‰๏ธ {c: 'test'}

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 or undefined and if either condition is met, 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