Skip to content

Instantly share code, notes, and snippets.

@kaplas
Created May 15, 2013 12:04
Show Gist options
  • Save kaplas/5583505 to your computer and use it in GitHub Desktop.
Save kaplas/5583505 to your computer and use it in GitHub Desktop.
A helper function (or underscore mixin) for omitting object properties in multiple levels
var deepCopy = function (value) {
return JSON.parse(JSON.stringify(value));
};
var omitAttributes = function (obj) {
var copy = deepCopy(obj);
var keys = Array.prototype.slice.call(arguments, 1);
function omitIfFound(obj, parts) {
if (parts.length > 0 && obj[parts[0]]) {
if (parts.length == 1) {
delete obj[parts[0]];
} else if (parts.length > 1) {
omitIfFound(obj[parts[0]], _.rest(parts));
}
}
}
_.each(keys, function (key) {
var parts = key.split('.');
omitIfFound(copy, parts);
});
return copy;
}
_.mixin({ omitAttributes: omitAttributes });
var obj = {
one: "lorem",
two: "ipsum",
three: {
one: "lorem",
two: "ipsum"
}
};
console.log( _(obj).omitAttributes('one', 'three.two') );
// Logs:
// { two: "ipsum", three: { one: "lorem" } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment