仅使用一个输入(即全局搜索)搜索对象中的多个属性

Vla*_*are 1 javascript arrays object reactjs

我正在尝试仅使用一个文本输入在reactjs 中构建对对象的通用/全局搜索。

我尝试了不同的方法,包括将字符串转换为数组,然后使用它来过滤我的对象。我设法对所有属性进行输入搜索,但当时只有一个。

const data = [
  {
    name:"Italy",
    title:"Best place for Pizza"
  },
  {
    name:"USA",
    title:"It is a federal state"
  }
]
export class MyApp extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      filteredData:[],
      filter:''
    }
    this.handleSearch.bind(this);
  }
  componentDidMount(){
    this.setState({
      filteredData:data
    })
  }

  handleSearch = (e) =>{
    const filter = e.target.value;

    this.setState({
      filter
    })
  }
  render(){
    var filteredData = data;
    var searchValue = this.state.filter;
    filteredData = filteredData.filter(country => {
      return['name', 'title'].some(key =>{
        return country[key].toString().toLowerCase().includes(searchValue)
      })
    })

    return (
      <div>
        <input type="search" onChange={(e) => this.handleSearch(e)}/>
        {
          filteredData.map(result =>{
              return <p>{result.name} | {result.title}</p>
          })
        }
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

我想要的是能够组合属性。例如:我希望能够输入“意大利最适合......的地方”并仍然得到结果。我不想仅限于输入“披萨最佳地点”或“意大利”来获取条目。

Akr*_*ion 5

您可以让您的搜索执行如下操作:

const data = [ { name:"Italy", title:"Best place for Pizza" }, { name:"USA", title:"It is a federal state" } ]

let search = (arr, str) => {
 return arr.filter(x => Object.values(x)
  .join(' ')
  .toLowerCase()
  .includes(str.toLowerCase()))
}

console.log(search(data, 'Italy best'))
console.log(search(data, 'USA it is'))
Run Code Online (Sandbox Code Playgroud)

这个想法是使用Array.filter并在内部获取对象的值(使用Object.values)(这里我们假设它们都是字符串)并将它们组合(通过Array.join)成一个字符串。然后使用Array.includes在其内部进行搜索。