Dafy
Dafy

Reputation: 183

How to fix "item[key].toLowerCase is not a function"

I want to add a search field in my dashboard and I have get api in this api have array and in the array I have objects so how I can do it in react what logic I should apply on it .

Here is the logic I apply on it but it returns error that

This is error:

item[key].toLowerCase is not a function

and this is logic i apply on it :

handleChange = event => {
    const lowercasedFilter = this.state.SearchResult.toLowerCase();
    this.state.data.bank_accounts.filter(item => {
    return Object.keys(item).some(key =>
      item[key].toLowerCase().includes(lowercasedFilter)
    );
  });
    this.setState({ SearchResult: event.target.value });
  };

Upvotes: 5

Views: 5466

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

As you showed that your single item looks like

{bank_accounts : [ { id: 1 , item_name: 'bankOne'} , {id: 2 , item_name:'bankTwo'} ] }

Here there are two keys id and item_name so item[key] for id is number and for this it throw error. First check the typeof the value and then use .toLowerCase

handleChange = event => {
    const lowercasedFilter = this.state.SearchResult.toLowerCase();
    this.state.data.bank_accounts.filter(item => {
    return Object.keys(item).some(key =>
      typeof item[key] === "string" && item[key].toLowerCase().includes(lowercasedFilter)
    );
  });
    this.setState({ SearchResult: event.target.value });
  };

Note: filter() doesnot mutate the original array. You need to store the result in another variable. like

const result  = this.state.data.bank_accounts.filter(....)

Upvotes: 7

Related Questions