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.

105 lines
2.1 KiB

4 years ago
  1. # `where()`
  2. The where method filters the collection by a given key / value pair:
  3. ```js
  4. const collection = collect([
  5. { product: 'Desk', price: 200, discounted: true },
  6. { product: 'Chair', price: 100, discounted: true },
  7. { product: 'Bookcase', price: 150, discounted: true },
  8. { product: 'Door', price: 100 },
  9. ]);
  10. const filtered = collection.where('price', 100);
  11. filtered.all();
  12. // [
  13. // { product: 'Chair', price: 100 },
  14. // { product: 'Door', price: 100 },
  15. // ]
  16. const discounted = collection.where('discounted');
  17. discounted.all();
  18. // [
  19. // { product: 'Desk', price: 200, discounted: true },
  20. // { product: 'Chair', price: 100, discounted: true },
  21. // { product: 'Bookcase', price: 150, discounted: true },
  22. // ]
  23. const notDiscounted = collection.where('discounted', false);
  24. discounted.all();
  25. // [
  26. // { product: 'Door', price: 100 },
  27. // ]
  28. ```
  29. > When working with nested objects `where()` method allows dot notated keys. E.g. `where('product.category', 'office-supplies')`
  30. > The where method also allows for custom comparisons:
  31. **Non-identity / strict inequality `(!==)`**
  32. ```js
  33. const filtered = collection.where('price', '!==', 100);
  34. filtered.all();
  35. // [
  36. // { product: 'Desk', price: 200 },
  37. // { product: 'Bookcase', price: 150 },
  38. // ]
  39. ```
  40. **Less than operator `(<)`**
  41. ```js
  42. const filtered = collection.where('price', '<', 100);
  43. filtered.all();
  44. // []
  45. ```
  46. **Less than or equal operator `(<=)`**
  47. ```js
  48. const filtered = collection.where('price', '<=', 100);
  49. filtered.all();
  50. // [
  51. // { product: 'Chair', price: 100 },
  52. // { product: 'Door', price: 100 },
  53. // ]
  54. ```
  55. **Greater than operator `(>)`**
  56. ```js
  57. const filtered = collection.where('price', '>', 100);
  58. filtered.all();
  59. // [
  60. // { product: 'Desk', price: 200} ,
  61. // { product: 'Bookcase', price: 150 },
  62. // ]
  63. ```
  64. **Greater than or equal operator `(>=)`**
  65. ```js
  66. const filtered = collection.where('price', '>=', 150);
  67. filtered.all();
  68. // [
  69. // { product: 'Desk', price: 200} ,
  70. // { product: 'Bookcase', price: 150 },
  71. // ]
  72. ```
  73. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/where.js)