invert.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var isIterateeCall = require('../internal/isIterateeCall'),
  2. keys = require('./keys');
  3. /** Used for native method references. */
  4. var objectProto = Object.prototype;
  5. /** Used to check objects for own properties. */
  6. var hasOwnProperty = objectProto.hasOwnProperty;
  7. /**
  8. * Creates an object composed of the inverted keys and values of `object`.
  9. * If `object` contains duplicate values, subsequent values overwrite property
  10. * assignments of previous values unless `multiValue` is `true`.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @category Object
  15. * @param {Object} object The object to invert.
  16. * @param {boolean} [multiValue] Allow multiple values per key.
  17. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
  18. * @returns {Object} Returns the new inverted object.
  19. * @example
  20. *
  21. * var object = { 'a': 1, 'b': 2, 'c': 1 };
  22. *
  23. * _.invert(object);
  24. * // => { '1': 'c', '2': 'b' }
  25. *
  26. * // with `multiValue`
  27. * _.invert(object, true);
  28. * // => { '1': ['a', 'c'], '2': ['b'] }
  29. */
  30. function invert(object, multiValue, guard) {
  31. if (guard && isIterateeCall(object, multiValue, guard)) {
  32. multiValue = undefined;
  33. }
  34. var index = -1,
  35. props = keys(object),
  36. length = props.length,
  37. result = {};
  38. while (++index < length) {
  39. var key = props[index],
  40. value = object[key];
  41. if (multiValue) {
  42. if (hasOwnProperty.call(result, value)) {
  43. result[value].push(key);
  44. } else {
  45. result[value] = [key];
  46. }
  47. }
  48. else {
  49. result[value] = key;
  50. }
  51. }
  52. return result;
  53. }
  54. module.exports = invert;