trx
trx

Reputation: 2157

Filter throws - Cannot read property 'toLowerCase' of null

I am trying to filter on the given input against the cached query result. Since I am filtering again user input value and database , I am converting them in to lower case and checking

result =  this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1);

It works fine until the cachedResult dont have NULL in that field. But if there is NULL how can I escape that record here.

Upvotes: 0

Views: 568

Answers (3)

rickdenhaan
rickdenhaan

Reputation: 11318

If f.prj is NULL then it cannot contain this.sV so that particular f should be filtered out, correct? In that case:

result = this.cachedResults.filter(f => f.prj && f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1);

Upvotes: 2

Batajus
Batajus

Reputation: 6257

You can do something like following to catch the null value in f.prj:

result =  this.cachedResults.filter(f => { 
    if (!f.prj) {
        return false; // Or return true, if you want
    }
    return f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1);
});

Upvotes: 1

Telmo Trooper
Telmo Trooper

Reputation: 5694

You got to check if the property prj exists in your object before using toLowerCase() on it.

result =  this.cachedResults.filter(f => {
  return f.prj ? (f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1) : false
});

Does this work for you?

If the problem is that (this.sV) does not exist, then you'll have to check that as well.

Upvotes: 1

Related Questions