Skip to content

Instantly share code, notes, and snippets.

@m-vdb
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-vdb/9367150 to your computer and use it in GitHub Desktop.
Save m-vdb/9367150 to your computer and use it in GitHub Desktop.
Undescore mixins : whereDeep
// inspired from _.matches
function deepMatch (attrs) {
return function (obj) {
var attrVal, objVal;
if (obj === attrs) return true; //avoid comparing an object to itself.
for (var key in attrs) {
attrVal = attrs[key];
objVal = obj[key];
if (_.isObject(attrVal) && _.isObject(objVal)) {
if (!deepMatch(attrVal)(objVal)) {
return false;
}
}
else if (attrVal !== objVal) {
return false;
}
}
return true;
};
}
_.extend(Backbone.Collection.prototype, {
// inspired from Collection.where
whereDeep: function(attrs) {
if (_.isEmpty(attrs)) {
return [];
}
return this.filter(function(model) {
return deepMatch(attrs)(model.attributes);
});
}
});
_.mixin({
// inspired from _.where
whereDeep: function(obj, attrs) {
return _.filter(obj, deepMatch(attrs));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment