Are you familiar with the collection in Laravel, then you will love this Collect.js, a Javascript counterpart of Laravel Collection. Collect.js offers an almost similar API to Laravel collections.
Installation
NPM
npm install collect.js --save
Yarn
yarn add collect.js
CDN
https://cdnjs.com/libraries/collect.js
Sample Methods
map()
The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:
const collection = collect([1, 2, 3, 4, 5]); const multiplied = collection.map(item => item * 2); multiplied.all(); // [2, 4, 6, 8, 10]
where()
The where method filters the collection by a given key/value pair:
const collection = collect([ { product: 'Desk', price: 200, discounted: true }, { product: 'Chair', price: 100, discounted: true }, { product: 'Bookcase', price: 150, discounted: true }, { product: 'Door', price: 100 }, ]); const filtered = collection.where('price', 100); filtered.all(); // [ // { product: 'Chair', price: 100 }, // { product: 'Door', price: 100 }, // ] const discounted = collection.where('discounted'); discounted.all(); // [ // { product: 'Desk', price: 200, discounted: true }, // { product: 'Chair', price: 100, discounted: true }, // { product: 'Bookcase', price: 150, discounted: true }, // ] const notDiscounted = collection.where('discounted', false); discounted.all(); // [ // { product: 'Door', price: 100 }, // ]
There are plenty of them, click here to read them in the git repo
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply