invertBy.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var baseIteratee = require('./_baseIteratee'),
  2. createInverter = require('./_createInverter');
  3. /** Used for built-in method references. */
  4. var objectProto = Object.prototype;
  5. /** Used to check objects for own properties. */
  6. var hasOwnProperty = objectProto.hasOwnProperty;
  7. /**
  8. * Used to resolve the
  9. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  10. * of values.
  11. */
  12. var nativeObjectToString = objectProto.toString;
  13. /**
  14. * This method is like `_.invert` except that the inverted object is generated
  15. * from the results of running each element of `object` thru `iteratee`. The
  16. * corresponding inverted value of each inverted key is an array of keys
  17. * responsible for generating the inverted value. The iteratee is invoked
  18. * with one argument: (value).
  19. *
  20. * @static
  21. * @memberOf _
  22. * @since 4.1.0
  23. * @category Object
  24. * @param {Object} object The object to invert.
  25. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  26. * @returns {Object} Returns the new inverted object.
  27. * @example
  28. *
  29. * var object = { 'a': 1, 'b': 2, 'c': 1 };
  30. *
  31. * _.invertBy(object);
  32. * // => { '1': ['a', 'c'], '2': ['b'] }
  33. *
  34. * _.invertBy(object, function(value) {
  35. * return 'group' + value;
  36. * });
  37. * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
  38. */
  39. var invertBy = createInverter(function(result, value, key) {
  40. if (value != null &&
  41. typeof value.toString != 'function') {
  42. value = nativeObjectToString.call(value);
  43. }
  44. if (hasOwnProperty.call(result, value)) {
  45. result[value].push(key);
  46. } else {
  47. result[value] = [key];
  48. }
  49. }, baseIteratee);
  50. module.exports = invertBy;