admin管理员组

文章数量:1335121

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

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 });
  };
Share Improve this question edited Apr 8, 2019 at 18:44 Joey Phillips 1,6252 gold badges16 silver badges22 bronze badges asked Apr 8, 2019 at 13:27 DafyDafy 1831 gold badge5 silver badges18 bronze badges 2
  • 6 item[key] is not a string. Can you please tell how a single item of array looks like? – Maheer Ali Commented Apr 8, 2019 at 13:29
  • {bank_accounts : [ { id: 1 , item_name: 'bankOne'} , {id: 2 , item_name:'bankTwo'} ] } i want to add search functionality on item_name – Dafy Commented Apr 8, 2019 at 13:35
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: javascriptHow to fix quotitemkeytoLowerCase is not a functionquotStack Overflow