Skip to content

Instantly share code, notes, and snippets.

@jhafner
Last active August 29, 2015 13:59
Show Gist options
  • Save jhafner/10675548 to your computer and use it in GitHub Desktop.
Save jhafner/10675548 to your computer and use it in GitHub Desktop.
Remove null, undefined, NaN, and empty strings from an object.
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}
@jhafner
Copy link
Author

jhafner commented Apr 14, 2014

JSFiddle: http://jsfiddle.net/VUAqT/1

EDIT: Updated JSFiddle example

@caedmonjudd
Copy link

Nice

@jhafner
Copy link
Author

jhafner commented Apr 14, 2014

Thanks to @vjeux for shortening the logic a bit!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment