Skip to content

Instantly share code, notes, and snippets.

@bzuillsmith
Last active August 29, 2015 14:00
Show Gist options
  • Save bzuillsmith/11335179 to your computer and use it in GitHub Desktop.
Save bzuillsmith/11335179 to your computer and use it in GitHub Desktop.
/**
* Removes {}, '', null, undefined values from objects and arrays recursively
* WARNING: This should be used only on objects that are known to not have
* circular refrences. User input can't have circular dependencies because
* it could not be JSON.stringified if it did, therefore user input is safe.
*/
function scrub(obj) {
for(var prop in obj) {
if(_.isArray(obj[prop])) {
obj[prop].forEach(function() {
scrub(obj[prop]);
});
var neswArray = [];
obj[prop].forEach(function(element) {
if(element !== null) {
newArray.push(element);
}
});
obj[prop] = newArray;
} else if(_.isObject(obj[prop])) {
scrub(obj[prop]);
if(_.isEmpty(obj[prop])) delete obj[prop];
} else if(obj[prop] === '' || obj[prop] === null || obj[prop] === undefined) {
delete obj[prop];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment