Skip to content

Instantly share code, notes, and snippets.

@aichholzer
Created February 7, 2018 21:59
Show Gist options
  • Save aichholzer/ea2a8d34cb579cb2911cb9a9f2aaf085 to your computer and use it in GitHub Desktop.
Save aichholzer/ea2a8d34cb579cb2911cb9a9f2aaf085 to your computer and use it in GitHub Desktop.
Remove all empty properties from an object, recursively.
const sample = {
a: 'Hello',
b: '', // Will be removed
c: null,
d: {
a: 1,
b: '', // Will be removed
c: 3,
d: {
a: 1,
b: '', // Will be removed
c: 'world'
},
e: null
}
}
/**
* Attach the cleaning method to the object's prototype chain.
*/
Object.defineProperties(Object.prototype, {
clean: {
configurable: true,
enumerable: false,
value: function clean (obj = this) {
Object.keys(obj).forEach(key => obj[key] !== null && typeof obj[key] === 'object' ? clean(obj[key]) :
obj[key] === '' && delete obj[key]);
return obj;
}
}
});
const cleanObject = sample.clean();
console.log(JSON.stringify(cleanObject, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment