如何在React中过滤多个值

Jon*_*as 1 javascript arrays sorting ecmascript-6 reactjs

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

代码

 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,
    });
  };
Run Code Online (Sandbox Code Playgroud)

对象数组

[
{firstName: 'Martin', lastName :'Jonas'},
{firstName:'Brad',lastName:'Mickle'},
{fitstName: 'Summer, lastName:'Bride'}
]
Run Code Online (Sandbox Code Playgroud)

Dre*_*ese 5

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

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

按功能搜索

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

用法

handleByNameChange = (e) => {
  const { value } = e.target;
  const updatedList = this.props.userData.allUsersForFilter;

  this.setState({
    byNameInputValue: value,
    items: searchBy(updatedList, ['firstName', 'lastName'], value),
  });
};
Run Code Online (Sandbox Code Playgroud)

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

附录 - 搜索组合全名

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

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

handleByNameChange = (e) => {
  const { value } = e.target;
  const updatedList = this.props.userData.allUsersForFilter;

  this.setState({
    byNameInputValue: value,
    items: searchBy(updatedList, ['firstName', 'lastName'], value),
  });
};
Run Code Online (Sandbox Code Playgroud)

沙箱演示中的所有代码

编辑过滤器数组多个值