-
-
Save StevenBlack/814992 to your computer and use it in GitHub Desktop.
// 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; | |
} | |
}); |
Fair point, for sure. Can you suggest a better function name? I couldn't think of anything better before settling on _.prune()
I'd say "filterObj" (for "filter" is occupied), or "comb" ;), or "pick".
Also, if you don;t mind, having dependency on jQuery lowers the area of application -- I'd replace it by "if (reference && typeof reference == 'object')" so far we have no _.isObject()
I like _.filterObj() ! Thanks. Done! I also incorporated your jQuery-agnostic suggestion. What was I thinking??
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.
I'd say it should kick out referenced keys, if it's called "prune", no?