Skip to content

Instantly share code, notes, and snippets.

@fonji
Created April 3, 2015 15:29
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 fonji/6c1895ed9b1cc2666128 to your computer and use it in GitHub Desktop.
Save fonji/6c1895ed9b1cc2666128 to your computer and use it in GitHub Desktop.
_.deepWhere
# _.deepWhere
# same as _.where but supports comparison of arrays as attributes
# https://gist.github.com/fonji/6c1895ed9b1cc2666128
#
# Example:
# _.deepWhere({foo: 'foo', bar: [{a: 'b'}]}, {bar: [{a: 'b'}]})
# Changelog:
# v0.1.0 creation (fonji)
# Returns whether an object has a given set of key:value pairs.
_.mixin(
deepIsMatch: (object, attrs) ->
keys = _.keys attrs
length = keys.length
return !length if object == null
obj = Object object
objKeys = _.keys obj
for key in keys
return false unless key in objKeys
if (_.isArray(attrs[key]) && _.isArray(obj[key])) ||
(_.isObject(attrs[key]) && _.isObject(obj[key]))
return false unless _.deepIsMatch(attrs[key], obj[key])
else
return false if attrs[key] != obj[key]
true
deepMatches: (attrs) ->
attrs = _.extendOwn({}, attrs)
return (obj) ->
return _.deepIsMatch(obj, attrs)
deepWhere: (obj, attrs) ->
_.filter obj, _.deepMatches(attrs)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment