Borislav Hadzhiev
Thu Oct 14 2021·2 min read
Photo by Jessica Polar
To remove all null 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 null
values using the delete
operator.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.
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.
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:
for...in
loop to iterate over the object.null
and delete the value
if it satisfies the condition.// 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.