Skip to content

Instantly share code, notes, and snippets.

@shaundon
Last active August 29, 2015 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shaundon/bb5e68cb0f926c538be7 to your computer and use it in GitHub Desktop.
Save shaundon/bb5e68cb0f926c538be7 to your computer and use it in GitHub Desktop.
Like underscore's omit function, but works deeply. Works on both objects and arrays. Requires underscore.
var deepOmit = function(input, propertyToRemove) {
var output = input;
if (_.isArray(input)) {
output = [];
_.each(input, function(arrayItem) {
output.push(deepOmit(arrayItem, propertyToRemove));
});
}
else if (_.isObject(input)) {
output = {};
_.each(_.keys(input), function(key) {
if (key !== propertyToRemove) {
output[key] = deepOmit(input[key], propertyToRemove);
}
});
}
return output;
}
/*
EXAMPLE:
deepOmit([
{
a: true,
remove: true
},
{
a: true,
remove: true,
b: {
a: true,
remove: true,
c: {
a: [
{
a: true,
remove: true
}
]
}
}
}
], 'remove');
WILL PRODUCE:
[
{
a: true
},
{
a: true,
b: {
a: true,
c: {
a: [
{
a: true
}
]
}
}
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment