Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 });
  };
like image 666
Syed Sadaif Rizvi Avatar asked Apr 08 '19 13:04

Syed Sadaif Rizvi


1 Answers

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(....)
like image 114
Maheer Ali Avatar answered Oct 15 '22 03:10

Maheer Ali