how to create React search filter for search multiple object key values

前端 未结 2 727
轻奢々
轻奢々 2021-02-01 21:44

I want to create a search filter for my data array.it has multiple objects and keys like this one,

[
    {
        \"fname\": \"Jayne\",
        \"lname\": \"Was         


        
2条回答
  •  隐瞒了意图╮
    2021-02-01 21:45

    You can keep a value filter in your component state and use that to see if it is contained as a substring in any of the array element properties.

    Example

    class App extends React.Component {
      state = {
        filter: "",
        data: [
          {
            fname: "Jayne",
            lname: "Washington",
            email: "jaynewashington@exposa.com",
            gender: "female"
          },
          {
            fname: "Peterson",
            lname: "Dalton",
            email: "petersondalton@exposa.com",
            gender: "male"
          },
          {
            fname: "Velazquez",
            lname: "Calderon",
            email: "velazquezcalderon@exposa.com",
            gender: "male"
          },
          {
            fname: "Norman",
            lname: "Reed",
            email: "normanreed@exposa.com",
            gender: "male"
          }
        ]
      };
    
      handleChange = event => {
        this.setState({ filter: event.target.value });
      };
    
      render() {
        const { filter, data } = this.state;
        const lowercasedFilter = filter.toLowerCase();
        const filteredData = data.filter(item => {
          return Object.keys(item).some(key =>
            item[key].toLowerCase().includes(lowercasedFilter)
          );
        });
    
        return (
          
    {filteredData.map(item => (
    {item.fname} {item.lname} - {item.gender} - {item.email}
    ))}
    ); } } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题