Created
May 13, 2020 08:07
-
-
Save emmanuelnk/92ea809113ef47447b945d1948760221 to your computer and use it in GitHub Desktop.
Clean js object by recursive removal of undefined, null, NaN and empty strings
This file contains hidden or 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
// A SO answer to https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript | |
// based off the recursive cleanEmpty function by @chickens. | |
// This one can also handle Date objects correctly | |
// and has a defaults list for values you want stripped. | |
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) { | |
if (defaults.includes(obj)) return | |
if (Array.isArray(obj)) | |
return obj | |
.map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v) | |
.filter(v => !defaults.includes(v)) | |
return Object.entries(obj).length | |
? Object.entries(obj) | |
.map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v])) | |
.reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) | |
: obj | |
} | |
// testing | |
console.log('testing: undefined \n', cleanEmpty(undefined)) | |
console.log('testing: null \n',cleanEmpty(null)) | |
console.log('testing: NaN \n',cleanEmpty(NaN)) | |
console.log('testing: empty string \n',cleanEmpty('')) | |
console.log('testing: empty array \n',cleanEmpty([])) | |
console.log('testing: date object \n',cleanEmpty(new Date(1589339052 * 1000))) | |
console.log('testing: nested empty arr \n',cleanEmpty({ 1: { 2 :null, 3: [] }})) | |
console.log('testing: comprehensive obj \n', cleanEmpty({ | |
a: 5, | |
b: 0, | |
c: undefined, | |
d: { | |
e: null, | |
f: [{ | |
a: undefined, | |
b: new Date(), | |
c: '' | |
}] | |
}, | |
g: NaN, | |
h: null | |
})) | |
console.log('testing: different defaults \n', cleanEmpty({ | |
a: 5, | |
b: 0, | |
c: undefined, | |
d: { | |
e: null, | |
f: [{ | |
a: undefined, | |
b: '', | |
c: new Date() | |
}] | |
}, | |
g: [0, 1, 2, 3, 4], | |
h: '', | |
}, [undefined, null])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment