Remove Empty String Values from an Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 27, 2022

banner

Photo from Unsplash

Remove Empty String Values from an Object #

To remove all empty string 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.
  3. Use the delete operator to delete each key with an empty string value.
index.js
const obj = { a: '', b: 'test', c: '', }; Object.keys(obj).forEach(key => { if (obj[key] === '') { 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: '', b: 'test', c: '', }; // 👇️ ['a', 'b', 'c'] console.log(Object.keys(obj));

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

We check if the value associated to the current key is equal to an empty string, and 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 empty string 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 an empty string.
  3. If the condition is met, use the delete operator to delete the key-value pair.
index.js
const obj = { a: '', b: 'test', c: '', }; for (const key in obj) { if (obj[key] === '') { 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 an empty string and if the condition is met, we delete the key-value pair using the delete operator.

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.