Skip to content

Instantly share code, notes, and snippets.

@chustedde
Last active December 20, 2015 09:40
Show Gist options
  • Save chustedde/6109580 to your computer and use it in GitHub Desktop.
Save chustedde/6109580 to your computer and use it in GitHub Desktop.
A mixin for underscore.js: Case-insensitive pick that returns an object with keys in the original case. Demo at http://jsfiddle.net/chustedde/Thv2w/
_.mixin({
// Case-insensitive pick that returns an object with keys in the original case
picki : function(obj, keys) {
var copy = {};
var objKeyList = _.keys(obj);
_.each(keys, function(key) {
_.each(objKeyList, function(o){
if (key.toString().toLowerCase() === o.toString().toLowerCase()) {
// o is from the list of keys extracted from the object, so
// it's in the original case
copy[o] = obj[o];
}
});
});
return copy;
}
});
var stuff = {"A":"hello", "B":"world"};
var theKeys = ["a", "b"];
alert("Despite the name, I'm very picky\n" + JSON.stringify(_.pick(stuff, theKeys)));
alert("I'm not picky!\n" + JSON.stringify(_.picki(stuff, theKeys)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment