Created
February 7, 2011 19:13
-
-
Save StevenBlack/814992 to your computer and use it in GitHub Desktop.
Underscore.js _mixin: _.prune
This file contains 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
// Return an object who's members match a reference array of keys | |
// reference=["b","c","f","r"]; | |
// obj={"a":1, "b":2, "c":3, "d":4, "r":18}; | |
// _.filterObj(obj, reference) | |
// => { b : 2, c : 3, r : 18} | |
_.mixin( { | |
filterObj : function( obj, reference ) { | |
if ( reference && typeof reference == 'object' ) { reference=_.keys( reference ); } | |
var intersect = _.intersect(reference, _.keys(obj)), retObj= {}; | |
_.map( intersect, function( el) { retObj[el]=obj[el];}) | |
return retObj; | |
} | |
}); |
Checking the typeof on the reference breaks the functionality, as typeof ['a', 'b', 'c'] === "object"
. I'd suggest not supporting passing a POJO in at all, and let the caller call _.keys(obj)
if that's what they really mean to do. Simplifies the interface and avoids needing to re-implement jQuery.isPlainObject(), which does a lot more juggling than just checking typeof.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like _.filterObj() ! Thanks. Done! I also incorporated your jQuery-agnostic suggestion. What was I thinking??