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)
创建一个函数,该函数接受要搜索的数组、要搜索的属性键数组以及要搜索的值。如果属性键数组为空,则可能不会发生任何过滤器,返回所有元素。
按功能搜索
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)
沙箱演示中的所有代码
| 归档时间: |
|
| 查看次数: |
1992 次 |
| 最近记录: |