forPage()
: The forPage() method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const forPage = collection.forPage(2, 3);
forPage.all();
// [4, 5, 6]
get()
: The
get() method returns the item at a given key or index. If the key or index does not exist, null is returned:
const collection = collect({
firstname: 'Mohamed',
lastname: 'Salah',
});
collection.get('lastname');
// Salah
collection.get('middlename');
// null
const collection = collect(['a', 'b', 'c']);
collection.get(1);
// b
You may optionally pass a default value as the second argument:
const collection = collect({
firstname: 'Mohamed',
lastname: 'Salah',
});
collection.get('middlename', 'default-value');
// default-value
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:
const collection = collect({
firstname: 'Mohamed',
lastname: 'Salah',
});
collection.get('middlename', () => 'default-value');
// default-value
const collection = collect({
name: 'Darwin Núñez',
number: 27,
});
collection.forget('number');
collection.all();
// {
// name: 'Darwin Núñez',
// }
Unlike most other collection methods, forget does not return a new modified collection; it modifies the collection it is called on.