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.

52 lines
978 B

4 years ago
  1. # `get()`
  2. The get method returns the item at a given key or index. If the key or index does not exist, `null` is returned:
  3. ```js
  4. const collection = collect({
  5. firstname: 'Chuck',
  6. lastname: 'Norris',
  7. });
  8. collection.get('lastname');
  9. // Norris
  10. collection.get('middlename');
  11. // null
  12. ```
  13. ```js
  14. const collection = collect(['a', 'b', 'c']);
  15. collection.get(1);
  16. // b
  17. ```
  18. You may optionally pass a default value as the second argument:
  19. ```js
  20. const collection = collect({
  21. firstname: 'Chuck',
  22. lastname: 'Norris',
  23. });
  24. collection.get('middlename', 'default-value');
  25. // default-value
  26. ```
  27. You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:
  28. ```js
  29. const collection = collect({
  30. firstname: 'Chuck',
  31. lastname: 'Norris',
  32. });
  33. collection.get('middlename', () => 'default-value');
  34. // default-value
  35. ```
  36. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/get.js)