Borislav Hadzhiev
Thu Oct 14 2021·2 min read
Photo by Tegan Mierle
To remove all empty string values from an object:
Object.keys()
method to get an array of the object's keys.forEach()
method to iterate over the array and delete all empty
string values using the delete
operator.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.
const obj = { a: '', b: 'test', c: '', }; // 👇️ ['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, 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.
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 empty string values from an object:
for...in
loop to iterate over the object.// Supported in IE 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 either condition is satisfied, we delete the key-value pair.