indexBy.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var createAggregator = require('../internal/createAggregator');
  2. /**
  3. * Creates an object composed of keys generated from the results of running
  4. * each element of `collection` through `iteratee`. The corresponding value
  5. * of each key is the last element responsible for generating the key. The
  6. * iteratee function is bound to `thisArg` and invoked with three arguments:
  7. * (value, index|key, collection).
  8. *
  9. * If a property name is provided for `iteratee` the created `_.property`
  10. * style callback returns the property value of the given element.
  11. *
  12. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  13. * style callback returns `true` for elements that have a matching property
  14. * value, else `false`.
  15. *
  16. * If an object is provided for `iteratee` the created `_.matches` style
  17. * callback returns `true` for elements that have the properties of the given
  18. * object, else `false`.
  19. *
  20. * @static
  21. * @memberOf _
  22. * @category Collection
  23. * @param {Array|Object|string} collection The collection to iterate over.
  24. * @param {Function|Object|string} [iteratee=_.identity] The function invoked
  25. * per iteration.
  26. * @param {*} [thisArg] The `this` binding of `iteratee`.
  27. * @returns {Object} Returns the composed aggregate object.
  28. * @example
  29. *
  30. * var keyData = [
  31. * { 'dir': 'left', 'code': 97 },
  32. * { 'dir': 'right', 'code': 100 }
  33. * ];
  34. *
  35. * _.indexBy(keyData, 'dir');
  36. * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
  37. *
  38. * _.indexBy(keyData, function(object) {
  39. * return String.fromCharCode(object.code);
  40. * });
  41. * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  42. *
  43. * _.indexBy(keyData, function(object) {
  44. * return this.fromCharCode(object.code);
  45. * }, String);
  46. * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  47. */
  48. var indexBy = createAggregator(function(result, value, key) {
  49. result[key] = value;
  50. });
  51. module.exports = indexBy;