Sometimes, we want to recursively remove null values from JavaScript object.
In this article, we’ll look at how to recursively remove null values from JavaScript object.
How to recursively remove null values from JavaScript object?
To recursively remove null values from JavaScript object, we can traverse all the properties of all nested objects and entries of all arrays and remove all null values.
For instance, we write:
const obj = {
"store": {
"book": [
null,
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
null,
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
}
],
"bicycle": {
"color": "red",
"price": null
}
}
}
const removeNulls = (obj) => {
const isArray = Array.isArray(obj);
for (const k of Object.keys(obj)) {
if (obj[k] === null) {
if (isArray) {
obj.splice(k, 1)
} else {
delete obj[k];
}
} else if (typeof obj[k] === "object") {
removeNulls(obj[k]);
}
if (isArray && obj.length === k) {
removeNulls(obj);
}
}
return obj;
}
const newObj = removeNulls(obj)
console.log(newObj)
We have the obj
object with some null values.
Then we define the removeNulls
function that takes the obj
object.
We check if obj
is an array.
And we loop through the keys with the for-of loop.
If obj[k]
is null and obj
is an array, we call splice
to remove the entry.
Otherwise, we use the delete
operator to remove the entry.
If obj[k]
is an object, then we call removeNulls
to traverse one level deeper into the object and do the same operations.
And if obj[k]
is an array and obj.length
is k
, then we call removeNulls
with obj
to remove null entries.
As a result, newObj
is:
{
"store": {
"book": [
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings"
}
],
"bicycle": {
"color": "red"
}
}
}
Conclusion
To recursively remove null values from JavaScript object, we can traverse all the properties of all nested objects and entries of all arrays and remove all null values.