Nitish Kumar
Nitish Kumar

Reputation: 6276

Table filters in Vuejs

I'm building a small application in vuejs where I'm having a filter something like this:

tableFilter: function () {
    const searchTerm = this.search.toLowerCase();
    const searchByType = this.search_by_tag.toLowerCase();
    if(this.contactStore.contactList)
    {
        return this.contactStore.contactList.data.filter((item) =>
            (item.first_name.toLowerCase().includes(searchTerm)
                || (item.last_name !==null && item.last_name.toLowerCase().includes(searchTerm))
                || (item.company.name !==null && item.company.name.toLowerCase().includes(searchTerm))
                || item.email.toLowerCase().includes(searchTerm)
                || (item.address !== null && item.address.toLowerCase().includes(searchTerm))
                || (item.city !== null && item.city.toLowerCase().includes(searchTerm))
                || (item.mobile !==null && item.mobile.toLowerCase().includes(searchTerm)))
        && ((item.profile !==null && item.profile.toLowerCase().includes(searchByType))
            || (item.company.type !== null && item.company.type.toLowerCase().includes(searchByType))
            || (item.company.sub_type !== null && item.company.sub_type.toLowerCase().includes(searchByType))));
    }
},

In this I've a property called item.company which can be null, so while implementing

(item.company.type !== null && item.company.type.toLowerCase().includes(searchByType))

it is throwing error:

Error in render function: "TypeError: Cannot read property 'type' of null"

I'm looking for a solution where I can have if-else to find out whether the item is having company or not, if property is available then it can do the filters respectively.

Thanks

Upvotes: 1

Views: 405

Answers (1)

Faly
Faly

Reputation: 13346

If you just want to fix the error:

|| (item.company && item.company.type !== null && item.company.type.toLowerCase().includes(searchByType))

But if you want to not filter by company if it is null:

|| (item.company ? && item.company.type !== null && item.company.type.toLowerCase().includes(searchByType) : true)

Upvotes: 2

Related Questions