findWhere.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var baseMatches = require('../internal/baseMatches'),
  2. find = require('./find');
  3. /**
  4. * Performs a deep comparison between each element in `collection` and the
  5. * source object, returning the first element that has equivalent property
  6. * values.
  7. *
  8. * **Note:** This method supports comparing arrays, booleans, `Date` objects,
  9. * numbers, `Object` objects, regexes, and strings. Objects are compared by
  10. * their own, not inherited, enumerable properties. For comparing a single
  11. * own or inherited property value see `_.matchesProperty`.
  12. *
  13. * @static
  14. * @memberOf _
  15. * @category Collection
  16. * @param {Array|Object|string} collection The collection to search.
  17. * @param {Object} source The object of property values to match.
  18. * @returns {*} Returns the matched element, else `undefined`.
  19. * @example
  20. *
  21. * var users = [
  22. * { 'user': 'barney', 'age': 36, 'active': true },
  23. * { 'user': 'fred', 'age': 40, 'active': false }
  24. * ];
  25. *
  26. * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
  27. * // => 'barney'
  28. *
  29. * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
  30. * // => 'fred'
  31. */
  32. function findWhere(collection, source) {
  33. return find(collection, baseMatches(source));
  34. }
  35. module.exports = findWhere;