Created
February 7, 2018 21:59
-
-
Save aichholzer/ea2a8d34cb579cb2911cb9a9f2aaf085 to your computer and use it in GitHub Desktop.
Remove all empty properties from an object, recursively.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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