You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.2 KiB

4 years ago
  1. var baseAssignValue = require('./_baseAssignValue'),
  2. createAggregator = require('./_createAggregator');
  3. /**
  4. * Creates an object composed of keys generated from the results of running
  5. * each element of `collection` thru `iteratee`. The corresponding value of
  6. * each key is the last element responsible for generating the key. The
  7. * iteratee is invoked with one argument: (value).
  8. *
  9. * @static
  10. * @memberOf _
  11. * @since 4.0.0
  12. * @category Collection
  13. * @param {Array|Object} collection The collection to iterate over.
  14. * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
  15. * @returns {Object} Returns the composed aggregate object.
  16. * @example
  17. *
  18. * var array = [
  19. * { 'dir': 'left', 'code': 97 },
  20. * { 'dir': 'right', 'code': 100 }
  21. * ];
  22. *
  23. * _.keyBy(array, function(o) {
  24. * return String.fromCharCode(o.code);
  25. * });
  26. * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
  27. *
  28. * _.keyBy(array, 'dir');
  29. * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
  30. */
  31. var keyBy = createAggregator(function(result, value, key) {
  32. baseAssignValue(result, key, value);
  33. });
  34. module.exports = keyBy;