【问题标题】:Trouble with React/JS filterReact/JS 过滤器的问题
【发布时间】:2019-06-24 04:59:25
【问题描述】:

我正在尝试实现一个过滤器功能,当用户在搜索栏中键入时,该功能能够在两个单独的 JSON 字段中进行搜索。搜索整个 JSON 会返回错误,如果我重复这个函数,两个相似的函数就会相互抵消。

我目前的过滤功能:

let filteredOArt = origArt.filter((origAItem) => {
                return origAItem.authors.toLowerCase().includes(this.state.search.toLowerCase())
            });

我希望能够在“作者”字段和“描述”字段中进行搜索。

在 React 渲染之前,我有这个函数监听状态:

updateSearch(event) {
    this.setState({ search: event.target.value }) 
}

那么我的搜索功能在React返回的一个输入字段中:

<h6>Search by author name: <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)} /></h6>

【问题讨论】:

  • 您能分享您的origArt 内容吗?如果我们看不到数据的结构,那真的很难说过滤器是否正常工作
  • 它是这样设置的:"articles": [ { "authors": "Iaizzo PA, Pozos RS:", "description": "运动诱发的生理动作震颤的振幅改变脚踝。”,“出版商”:“应用生理学杂志 53:1164-1170”,“日期”:“1982。”,“journalID”:“PMID:7174409”},

标签: javascript json reactjs filtering


【解决方案1】:

你可以像这样调整函数

let filteredOArt = origArt.filter((origAItem) => {
       return (
(origAItem.authors.toLowerCase().includes(this.state.search.toLowerCase())||

(origAItem.description.toLowerCase().includes(this.state.search.toLowerCase())
       )
)
        });

【讨论】:

  • 希望对您有所帮助!
  • 谢谢你,它工作得很好,并且使代码易于阅读!
【解决方案2】:

您实际上可以对这两个字段进行过滤。

假设你有你的 searchValue 和你的数组,你可以通过这种方式过滤对象:

const filterByAuthorOrDescription = (searchValue, array) =>
  array.filter(
    item =>
      item.authors.toLowerCase().includes(searchValue.toLowerCase()) ||
      item.description.toLowerCase().includes(searchValue.toLowerCase())
  );
const filtered = filterByAuthorOrDescription(this.state.search, articles);

filtered 现在将包含一个对象数组,其中包含您可以映射的描述或作者中的 searchValue。

【讨论】:

    【解决方案3】:

    您可以使用some 来检查过滤器是否至少对一个字段为正:

    let filteredOArt = origArt.filter(origAItem => ['authors', 'description'].some(field => origAItem.[field].toLowerCase().includes(this.state.search.toLowerCase())))
    

    只需遍历您要使用的不同字段名称。

    如果提到的任何字段包含您的字符串,Some 将返回true,并避免在您的代码中重复。

    长语法:

    origArt.filter(origAItem => {
        return ['authors', 'description'].some(field => origAItem.[field].toLowerCase().includes(this.state.search.toLowerCase()))
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      相关资源
      最近更新 更多