Remove all Undefined Values from an Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 26, 2022

banner

Photo from Unsplash

Remove all Undefined Values from an Object in JavaScript #

To remove all 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 undefined values using the delete operator.
index.js
const obj = { a: undefined, b: 'test', c: undefined, }; Object.keys(obj).forEach(key => { if (obj[key] === undefined) { delete obj[key]; } }); console.log(obj); // 👉️ {b: 'test'}

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

index.js
const obj = { a: undefined, b: 'test', c: undefined, }; // 👇️ ['a', 'b', 'c'] console.log(Object.keys(obj))

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

On each iteration, we check if the value associated to the current key is equal to undefined.

If the condition is met, we use the delete operator to delete the key-value pair.

Alternatively, you can use the for...in loop.

To remove all undefined values from an object:

  1. Use the for...in loop to iterate over the object.
  2. On each iteration, check if the current value is equal to undefined.
  3. If the condition is met, use the delete operator to delete the key-value pair.
index.js
const obj = { a: undefined, b: 'test', c: undefined, }; for (const key in obj) { if (obj[key] === undefined) { delete obj[key]; } } console.log(obj); // 👉️ {b: '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 undefined, and if the condition is satisfied, we delete the key-value pair.

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.