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.

55 lines
1.1 KiB

4 years ago
  1. # `keyBy()`
  2. The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:
  3. ```js
  4. const collection = collect([
  5. {
  6. product: 'Chair',
  7. manufacturer: 'IKEA',
  8. },
  9. {
  10. product: 'Desk',
  11. manufacturer: 'IKEA',
  12. },
  13. {
  14. product: 'Chair',
  15. manufacturer: 'Herman Miller',
  16. },
  17. ]);
  18. const keyed = collection.keyBy('manufacturer');
  19. keyed.all();
  20. // {
  21. // IKEA: {
  22. // product: 'Desk',
  23. // manufacturer: 'IKEA',
  24. // },
  25. // 'Herman Miller': {
  26. // product: 'Chair',
  27. // manufacturer: 'Herman Miller',
  28. // },
  29. // }
  30. ```
  31. You may also pass a callback to the method. The callback should return the value to key the collection by:
  32. ```js
  33. const upperCased = collection.keyBy(item => item.manufacturer.toUpperCase());
  34. upperCased.all();
  35. // {
  36. // IKEA: {
  37. // product: 'Desk',
  38. // manufacturer: 'IKEA',
  39. // },
  40. // 'HERMAN MILLER': {
  41. // product: 'Chair',
  42. // manufacturer: 'Herman Miller',
  43. // },
  44. // }
  45. ```
  46. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/keyBy.js)