[Vuejs]-Preventing higher order array methods from throwing an error

3👍

This doesn’t seem to have anything to do with arrays.

From your code I understand conversationMember.Name is supposed to be a string (because you’re calling .toLowerCase() on it), which means incudes here is not Array.prototype.includes, but String.prototype.includes, especially since self.conversationSearchTerm seems to also be a string (you’re also calling .toLowerCase() on it).

So, the problem is you’re using includes on something that should be a string but is not. The simple fix is to default it to an empty string when it’s falsy:

return (conversationMember.Name || '').toLowerCase().includes(
  (self.conversationSearchTerm || '').toLowerCase()
);

As a side note, you don’t need the var self = this;. this is available inside your filter since the filter is an arrow function. So your function (I’m guessing it’s a computed but it can as well be a method) could look like this:

filteredConversations() {
  return this.conversations.filter(c => 
    c.MembershipData.some(md => 
      (md.Name || '').toLowerCase().includes(
        (this.conversationSearchTerm || '').toLowerCase()
      )
    )
  );
}

One last note: this will still fail if any of your conversations does not have a MembershipData holding an array. To get around that, you could default it to an empty array on the fly:

 ...
   (c.MembershipData || []).some(md => 
 ...

As expected, any conversation without an array in MembershipData will be filtered out by the function (not included in the result) – because .some(condition) will return false when called on an empty array.

👤tao

Leave a comment