Skip to content

Instantly share code, notes, and snippets.

@StevenBlack
Created February 7, 2011 19:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenBlack/814992 to your computer and use it in GitHub Desktop.
Save StevenBlack/814992 to your computer and use it in GitHub Desktop.
Underscore.js _mixin: _.prune
// 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;
}
});
@dvv
Copy link

dvv commented Feb 8, 2011

I'd say it should kick out referenced keys, if it's called "prune", no?

@StevenBlack
Copy link
Author

Fair point, for sure. Can you suggest a better function name? I couldn't think of anything better before settling on _.prune()

@dvv
Copy link

dvv commented Feb 8, 2011

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()

@StevenBlack
Copy link
Author

I like _.filterObj() ! Thanks. Done! I also incorporated your jQuery-agnostic suggestion. What was I thinking??

@pd
Copy link

pd commented Feb 22, 2011

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