Created
May 15, 2013 12:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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