【问题标题】:How to filter multiple values in React如何在 React 中过滤多个值
【发布时间】:2020-11-03 10:20:33
【问题描述】:

我正在尝试搜索一个数组,但同时我可以搜索我想要实现的名字,我也想包含姓氏。例如,如果用户搜索包含姓氏或名字我想显示数据。有人可以帮我解决这个问题。

代码

 handleByNameChange = (e) => {
    let value = e.target.value;
    let updatedList = this.props.userData.allUsersForFilter;
    updatedList = updatedList.filter(function (item) {
      return item.firstName.toLowerCase().search(value.toLowerCase()) !== -1;
    });

    this.setState({
      byNameInputValue: value,
      items: updatedList,
    });
  };

对象数组

[
{firstName: 'Martin', lastName :'Jonas'},
{firstName:'Brad',lastName:'Mickle'},
{fitstName: 'Summer, lastName:'Bride'}
]

【问题讨论】:

    标签: javascript arrays reactjs sorting ecmascript-6


    【解决方案1】:

    创建一个函数,该函数接受要搜索的数组、要搜索的属性键数组以及要搜索的值。如果属性键数组为空,则可能不会出现过滤器,返回所有元素。

    • 如果满足使用属性键条件之一,则使用 array:some 返回真/假。
    • 使用 string::includes 测试字符串是否包含子字符串。

    搜索功能

    const searchBy = (arr = [], searchKeys = [], value = '') => {
      return arr.filter(item =>
        searchKeys.length ? searchKeys.some(key =>
          (item[key] || "").toLowerCase().includes(value.toLowerCase())
        ) : true
      );
    };
    

    用法

    handleByNameChange = (e) => {
      const { value } = e.target;
      const updatedList = this.props.userData.allUsersForFilter;
    
      this.setState({
        byNameInputValue: value,
        items: searchBy(updatedList, ['firstName', 'lastName'], value),
      });
    };
    

    const data = [
      { firstName: "Martin", lastName: "Jonas" },
      { firstName: "Brad", lastName: "Mickle" },
      { firstName: "Summer", lastName: "Bride" },
      { firstName: "Axel", lastName: "Rod" },
      { firstName: "Mike", lastName: "Haxel" }
    ];
    
    const searchBy = (arr = [], searchKeys = [], value = '') => {
      return arr.filter(item =>
        searchKeys.length ? searchKeys.some(key =>
          (item[key] || "").toLowerCase().includes(value.toLowerCase())
        ) : true
      );
    };
    
    console.log(searchBy(data, [], "Martin"));
    console.log(searchBy(data, ["lastName"], ""));
    console.log(searchBy(data, ["firstName"], "Martin"));
    console.log(searchBy(data, ["firstName"], "Summer"));
    console.log(searchBy(data, ["firstName", "lastName"], "ax"));

    附录 - 搜索组合全名

    const searchByName = (arr = [], value = "") => {
      return arr.filter(({ firstName = '', lastName = '' }) =>
        [firstName, lastName, `${firstName} ${lastName}`].some(el =>
          el.toLowerCase().includes(value.toLowerCase())
        )
      );
    };
    

    尝试匹配名字或姓氏,然后是全名

    const data = [
      { firstName: "Martin", lastName: "Jonas" },
      { firstName: "Brad", lastName: "Mickle" },
      { firstName: "Summer", lastName: "Bride" },
      { firstName: "Axel", lastName: "Rod" },
      { firstName: "Mike", lastName: "Haxel" }
    ];
    
    const searchByName = (arr = [], value = "") => {
      return arr.filter(({ firstName = '', lastName = '' }) =>
        [firstName, lastName, `${firstName} ${lastName}`].some(el =>
          el.toLowerCase().includes(value.toLowerCase())
        )
      );
    };
    
    console.log(searchByName(data, "Martin"));
    console.log(searchByName(data, ""));
    console.log(searchByName(data, "Summer"));
    console.log(searchByName(data, "ax"));
    console.log(searchByName(data, "Mike Ha"));

    沙盒演示中的所有代码

    【讨论】:

    • 感谢您的回答,例如,当我在输入中输入内容时(Mike Haxel)。当我输入名字并做空格时,它什么都不返回。你能检查一下吗
    • @Jonas,啊,就像您在搜索字符串文字“Mike Haxel”一样?为此,上述通用的每字段解决方案将无法正常工作,但您将执行类似于`${item.firstName} ${item.lastName}`.toLowerCase().includes(value.toLowerCase()) 的条件测试,在其中构建一个“fullName”字符串进行测试。希望这是有道理的。
    • @Jonas 答案已更新,包括运行代码和框。
    • 感谢@DrewReese 的深入回答
    • @DrewReese 出现错误,TypeError: Cannot read property 'toLowerCase' of null .. on this line el.toLowerCase().includes(value.toLowerCase())
    【解决方案2】:

    使用some 方法组合firstName 和lastName 数组。 (或者返回 (firstName check || lastName check)

    data = [
      { firstName: "Martin", lastName: "Jonas" },
      { firstName: "Brad", lastName: "Mickle" },
      { firstName: "Summer", lastName: "Bride" },
    ];
    value = "ride";
    updatedList = data.filter(({ firstName, lastName }) =>
      [firstName, lastName].some(
        (name) => name.toLowerCase().search(value.toLowerCase()) !== -1
      )
    );
    
    console.log(updatedList);

    【讨论】:

    • 我收到此错误 TypeError: Cannot read property 'toLowerCase' of null
    • @Jonas 您的数据数组属性名称中有一个拼写错误,“fitstName”与“firstName”一样。我们中的一些人可能已经纠正了它,但没有说出来。
    • @DrewReese,你是对的。谢谢你。我应该提到的。 jonas,此代码示例,具有固定数据。
    【解决方案3】:

    这是您要找的吗?

    const data = [
    {firstName: 'Martin', lastName :'Jonas'},
    {firstName:'Brad',lastName:'Mickle'},
    {firstName:'Summer',lastName:'Bride'}
    ]
    
    //anyName , which might be first Name or last Name
    
    function filterData(anyName){
            const res = data.filter(name => (name.firstName.includes(anyName)||name.lastName.includes(anyName)))
            return res;
    }
    
    
    console.log(filterData('ride'))

    【讨论】:

      【解决方案4】:

      你可以这样做:

      const updatedList = [
        {firstName: 'Martin', lastName :'Jonas'},
        {firstName:'Brad',lastName:'Mickle'},
        {firstName: 'Summer', lastName:'Bride'}
        ];
      
        updatedList = updatedList.filter(function (item) {
          return item.firstName.toLowerCase().search(value.toLowerCase()) !== -1 || 
           item.lastName.toLowerCase().search(value.toLowerCase()) !== -1;
        });
      

      【讨论】:

      • TypeError: 无法读取属性 'toLowerCase' of null
      • 在此处检查这一行 >{>fitstName<: lastname:>
      【解决方案5】:
      updatedList = updatedList.filter(function (item) {
          if(value) {
              return item.firstName.toLowerCase().indexOf(value.toLowerCase()) > -1 || item.lastName.toLowerCase().indexOf(value.toLowerCase()) > -1;
            } else {
            return "";
            }
      });
      

      这是一个非常基本的检查,简洁明了,它检查名字或姓氏值是否与提供的项目匹配。

      【讨论】:

      • TypeError: 无法读取属性 'toLowerCase' of null
      • 更新了我的评论。请再次检查@Jonas
      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      相关资源
      最近更新 更多