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

时间:2019-04-08 13:27:48

标签: javascript reactjs

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 });
  };

2 个答案:

答案 0 :(得分:2)

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(....)

答案 1 :(得分:-1)

Filter returns the new array. You need to return true for each element that matches with the searched item.

handleChange = event => {
    const lowercasedFilter = event.target.value.toLowerCase();
    const filteredList = this.state.data.bank_accounts.filter(item => {
      const name = item.item_name.toLowerCase();
      return (name.indexOf(lowercasedFilter) > -1)
    });
    this.setState({ SearchResult: filteredList });
  };