How to remove null or undefined from a nested object in Javascript
Jasser Mark Arioste
Sometimes we need to remove null
or undefined
properties from an object in JavaScript. Maybe to clean the data from the server or to pass clean data to the server or database.
Remove null/undefined properties using pure JavaScript #
To remove null or undefined properties from an object using vanilla JavaScript, we can use a combination of Object.entries
and array.filter
and recursion.
//index.js const data = { prop1: 'hello', prop2: undefined, prop3: null, prop4: { innerProp: null, innerProp2: 'world', }, }; function removeEmpty(data) { //transform properties into key-values pairs and filter all the empty-values const entries = Object.entries(data).filter(([, value]) => value != null); //map through all the remaining properties and check if the value is an object. //if value is object, use recursion to remove empty properties const clean = entries.map(([key, v]) => { const value = typeof v == 'object' ? removeEmpty(v) : v; return [key, value]; }); //transform the key-value pairs back to an object. return Object.fromEntries(clean); } const clean = removeEmpty(data); console.log(clean); //{"prop1":"hello","prop4":{"innerProp2":"world"}}
123456789101112131415161718192021222324252627282930
The good thing about the method above is it does not modify the old object and instead returns us a new object.
Conclusion #
We have successfully created a function to remove null or undefined properties from a deeply nested object in javascript.
If you like tutorials like these, please leave a like or consider subscribing to our newsletter down below!
Credits: Image by MF Gallery from Pixabay