Skip to content

Instantly share code, notes, and snippets.

@mikertjones
Created November 1, 2012 16:59
Show Gist options
  • Save mikertjones/3995028 to your computer and use it in GitHub Desktop.
Save mikertjones/3995028 to your computer and use it in GitHub Desktop.
Underscore.js_mixin:_.altWhere
// Return an object who's members match choice of parameters
// Extends underscore _.where concept
// params={gender:'M',status:'Staff|Volunteer'};
// obj=[{gender:'M',status:'Staff',name:'Jack'},{gender:'F',status:'Volunteer',name:'Susan'},{gender:'M',status:'Student',name:'Peter'}];
// _.filterObj(obj, params)
// => [{gender:'M',status:'Staff',name:'Jack'}]
_.mixin({
altWhere:function(obj, attrs) {
if (_.isEmpty(attrs)) return [];
return _.filter(obj, function(value) {
var foundArr=[],foundIdx=0,idxCount;
for (var key in attrs) {
foundArr[foundIdx] = false;
var i,thisValParts = attrs[key].split(/\|/); // you could use a different delimiter
for(i=0;i<thisValParts.length;i++){
if(thisValParts[i] ===value[key]) foundArr[foundIdx] = true;
}
foundIdx ++;
} // end for key in attrs
for(idxCount=0;idxCount<foundArr.length;idxCount++){
if(foundArr[idxCount]==false) return false;
}
return true; //true;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment