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.

100 lines
1.3 KiB

4 years ago
  1. # `pluck()`
  2. The pluck method retrieves all of the values for a given key:
  3. ```js
  4. const collection = collect([
  5. {
  6. id: 78,
  7. name: 'Aeron',
  8. },
  9. {
  10. id: 79,
  11. name: 'Embody',
  12. },
  13. ]);
  14. const plucked = collection.pluck('name');
  15. plucked.all();
  16. // ['Aeron', 'Embody']
  17. ```
  18. You may also specify how you wish the resulting collection to be keyed:
  19. ```js
  20. const collection = collect([
  21. {
  22. id: 78,
  23. name: 'Aeron',
  24. },
  25. {
  26. id: 79,
  27. name: 'Embody',
  28. },
  29. ]);
  30. const plucked = collection.pluck('name', 'id');
  31. plucked.all();
  32. // {
  33. // 78: 'Aeron',
  34. // 79: 'Embody',
  35. // }
  36. ```
  37. You can use "dot notation" to access nested values
  38. ```js
  39. const collection = collect([
  40. {
  41. name: 'John',
  42. roles: [
  43. {
  44. name: 'Editor',
  45. },
  46. {
  47. name: 'Admin',
  48. },
  49. ],
  50. },
  51. ]);
  52. const plucked = collection.pluck('roles.0.name');
  53. plucked.all();
  54. // ['Editor']
  55. ```
  56. "Dot notation" supports "wildcard"
  57. ```js
  58. const collection = collect([
  59. {
  60. name: 'John',
  61. roles: [
  62. {
  63. name: 'Editor',
  64. },
  65. {
  66. name: 'Admin',
  67. },
  68. ],
  69. },
  70. ]);
  71. const plucked = collection.pluck('roles.*.name');
  72. plucked.all();
  73. // [
  74. // [
  75. // 'Editor',
  76. // 'Admin',
  77. // ],
  78. // ]
  79. ```
  80. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/pluck.js)