具有多个字符串值的过滤器对象

问题描述

我正在尝试使用与用户在输入上写入的字符串匹配的元素来过滤对象。我正在使用 autosuggest 来呈现建议。 这是我目前所拥有的:

<Autosuggest
                  suggestions={options}
                  onSuggestionsFetchRequested={fetchOptions}
                  onSuggestionsClearRequested={() => setoptions([])}
                  getSuggestionValue={getSuggestionValue}
                  renderSuggestion={renderSuggestion}
                  inputProps={inputProps}
                />

我有一个道具上的所有选项,我想过滤这些选项以显示与输入匹配的选项,这就是我现在过滤的方式:

const fetchOptions = async ({ value }) => {
    setSelected(null);

    value = value.toLowerCase();
    const results = props.completeOptions.filter(
      (v) => v.label.toLowerCase().indexOf(value) != -1
    );
    setoptions(limit(results)); //Here i'm setting the options hook that i use on the suggestions
  };

这是我在 redux 上的 completeOptions prop 的值:

[
        {
            "id": "1","label": "33 Red Case"
        },{
            "id": "2","label": "Blue Case"
        },{
            "id": "3","label": "1 Green Case"
        },...
]

现在,如果我输入例如“Case”(这显示了 3 个标签),如果我使用“33”(显示一个),这将完美地工作,但是如果我输入“33 case”不显示任何东西,它应该显示一个选项。

我该如何解决这个问题?是否方便拆分值逐个查找,是不是整个字符串一起查找比较好?

解决方法

您的过滤器逻辑看起来不错,当我们只想检查子字符串是否存在时,我们应该使用 v.label.toLowerCase().split(" ").includes(value)

v.label.toLowerCase().split(" ").some(val => val.includes(value)

在上面的例子中,我们将字符串拆分为数组并将子字符串与每个标记匹配

indexOf 处理子字符串检查的方式略有不同,可能会导致不希望的结果。

,

因为您正在寻找完整的搜索词匹配。您可以在 every 中使用 javascript 来检查搜索词并在所有搜索词都匹配时返回 true。您可以检查此代码。

const searchData = value.toLowerCase().split(" ");
const results = props.completeOptions.filter(v => searchData.every(word => v.label.toLowerCase().includes(word)));