Last active
August 29, 2015 13:59
-
-
Save jhafner/10675548 to your computer and use it in GitHub Desktop.
Remove null, undefined, NaN, and empty strings from an object.
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
var settings = { | |
foo: "", | |
bar: undefined, | |
hello: "world", | |
baz: NaN, | |
what: null, | |
test: "string", | |
zero: 0, | |
falseVal: false | |
} | |
function removeEmptyElements(object) { | |
for (var key in object) { | |
var value = object[key]; | |
if (value === '' || | |
value !== value || /* NaN */ | |
value == null /* null or undefined */) { | |
delete object[key] | |
} | |
} | |
} | |
removeEmptyElements(settings); | |
console.log(settings) // Returns: Object {hello: "world", test: "string", zero: 0, falseVal: false} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to @vjeux for shortening the logic a bit!