Skip to content

Instantly share code, notes, and snippets.

@kewogc
Forked from shaundon/deep_omit.js
Last active August 29, 2015 14:26
Show Gist options
  • Save kewogc/60f58aa8c6136977436c to your computer and use it in GitHub Desktop.
Save kewogc/60f58aa8c6136977436c 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