简体   繁体   中英

ReactJS Search input by multiple values

I have a search and select filters on my page. The issue that I am having is that I can't seem to make the search work with multiple json values.

Example value is { "id": "1", "role": "teacher", "subject": "mathematics", "name": "Jonathan Kovinski" } and I want to be able to use key and values.

I've tried using some other question about combining json key and value into a single array and passing it to the search filter but it didn't work.

text = data.filter(info => {
  return Object.keys(info).map(function(key) {
    var singleOne = JSON.stringify(info[key]);
    console.log(info, "This is the json one")
  }).toLowerCase().match(searchString);
});

Here is a link to a JS Fiddle that I've created with all of my code.

I am trying to set my search bar to use all keys and values for searching and sorting data.

i would suggest you put the filtered data in a seperate key in the state in case you want to revert to the original result, use the Obeject.values instead of Object.keys and filter the data in the handleChange function,

here's a working code :

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      data: [],
      searchString: "",
      filtered: []
    };
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  handleChange(e) {
    var value = e.target.value;
    this.setState({
      searchString: value,
      filtered: this.state.data.filter(e =>
        Object.values(e)
          .join(" ")
          .toLowerCase()
          .match(value)
      )
    });
  }

  fetchData() {
    fetch("https://api.myjson.com/bins/lo3ls")
      .then(response => response.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json,
          filtered: json
        });
      })
      .catch(error => console.log("parsing failed", error));
  }

  render() {
    var { isLoaded, data } = this.state;
    const searchString = this.state.searchString.trim().toLowerCase();
    let text = this.state.data;
    console.log(text);
    if (searchString.length > 0) {
      text = text.filter(info => {
        return info.role.toLowerCase().match(searchString);
      });
    }
    return (
      <div>
        <input
          type="text"
          id="searchbar"
          value={this.state.searchString}
          onChange={this.handleChange}
          placeholder="Search"
          name="device"
        />

        <select className="category-select" name="categories" onChange={this.handleChange}>
          {data.map(info => (
            <option value={info.role}>{info.role}</option>
          ))}
        </select>
        {/* map through the filtered ones*/}
        {this.state.filtered.map(info => (
          <div className="display">
            <span className="role">Role: {info.role}</span>
            <span> Name: {info.name}</span>
            <span>, Subject: {info.subject}</span>
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<Hello name="World" />, document.getElementById("container"));

Actually, I read all of your code in Fiddle, But I proffer Fuse to you. Use it inside your code in componentDidMount and implement your search. it is very easy and handy.

const options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [
    "title",
    "author.firstName"
  ]
};

const fuse = new Fuse(list, options); // "list" is the item array
const result = fuse.search(""); // put your string inside double quotation

The result is your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM