JavaScript Collection Implementation

JavaScriptPosted on

JavaScript provides a useful functionality for arrays/objects by default, but many times the data we have to work with requires more complex solutions than the default. In the back-end world, Laravel has its collection layer what’s an incredible tool and working very well. So we decided to implement our functionality in JS as well. You can find the code in this GitHub repo.

Importing the Collection Class

In our code, all we have to do is import the class and assign it as a global to use it anywhere.

import Collection from './Collection';
window.Collection = Collection;

From this point, we can use the collection class anywhere in our code.

Some Handy Methods

All we have to do is initialize a new collection with the items we want to use. These are simple methods, and you can find all of them in the GitHub repo.

let items = new Collection([1, 2, 3, 4]);

all()

It lists all the items of the collection as a plain array.

items.all(); // [1, 2, 3, 4, 5]

first()

It returns with the first item of the collection.

items.first(); // 1

contains()

It determines if the given item is in the collection or not.

items.contains(3); // true

items.contains(6); // false

forget()

It removes the item associated with the given key. Also you can pass an array of keys.

items.forget(1); // [1, 3, 4, 5]

items.forget([0, 2, 4]); // [2, 4]

Integrating with Vue

After we assigned the collection class as a global in our window object, we can reference it easily anywhere even in our Vue instance.

new Vue({
    data() {
        return {
            items: new Collection([{name: 'Joe'}, {name: 'Jane'}])
        };
    }  
})
<li v-for="user in items.all()">{{ user.name }}</li> // Joe, Jane

Summary

Our goal was not to implement all the functionality of the collection class of Laravel but migrate some methods what we need. We are planning to add more functionality in the future.

The collection approach is convenient when you need to work with a bit more complex data structure like sortable, filterable data tables. Also it’s easy to integrate with Vue or any modern JS framework.

You can use in any project you want to. You can find the source code in this GitHub repo.

Also, if you are curious about Laravel’s collection API, you can read the documentation.

If you are looking of a full solution what implements Laravel’s API of collections, this script may be a good choice.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in JavaScript category