javascript - 创建一个可以在对象数组中搜索元素的函数?
问题描述
我有这个对象数组:
var person = [
{firstName: "Josh", lastName: "Doe", age: 50, eyeColor: "blue"},
{firstName: "Jake", lastName: "Denver", age: 34, eyeColor: "blue"},
{firstName: "Sam", lastName: "Kiszka", age: 20, eyeColor: "brown"}
];
我必须创建一个函数,在其中写下一个名称,该函数可以告诉你它是否是对象数组的一部分。有人可以帮助我吗?
解决方案
此函数将返回与传递的参数(搜索字符串)匹配firstName
或匹配的对象:lastName
input
function filterPersons(input) {
const results = person.filter(function(p){
if (input.length == 0) return false;
return (p.firstName+' '+p.lastName).match(new RegExp(input, 'i'));
});
return results;
};
空数组意味着:没有人的名字或姓氏与输入字符串匹配。
该功能用于此过滤解决方案,您可以运行:
// your input array
const person = [
{firstName: "Josh", lastName: "Doe", age: 50, eyeColor: "blue"},
{firstName: "Jake", lastName: "Denver", age: 34, eyeColor: "blue"},
{firstName: "Sam", lastName: "Kiszka", age: 20, eyeColor: "brown"}
];
// the function you are looking for
const filterPersons = function(input) {
const results = person.filter(function(p){
if (input.length == 0) return false;
return (p.firstName+' '+p.lastName).match(new RegExp(input, 'i'));
});
return results;
};
// this shows the filtering in action
window.onload = function(){
const input = document.getElementById('val');
const output = document.getElementById('out');
input.addEventListener("keyup", function (ev) {
const val = ev.target.value;
// here we are calling the filter function
const results = filterPersons(val);
if (results.length > 0) {
output.innerHTML = 'Yes! ' + JSON.stringify(results);
} else {
output.innerHTML ='No!';
}
});
}
<input id="val" />
<h3>included?</h3>
<div id="out">
</div>
推荐阅读
- ios - 具有系统字体、粗体和字距调整的 UIButton 子类
- swift - 快速通知未触发
- excel - 多次运行后重复宏出错
- google-chrome - Chrome 过滤掉 SameSite:None 安全 cookie
- xml - 将一列中的 XML 对象解析为多行,并允许在最后一行之后出现下一个 XML 对象
- javascript - 如何连接到数组状态的最后一项?
- javascript - 表单验证不适用于名称输入框
- datetime - 如何更改 showDatePicker 输入格式颤动
- php - 无法使用 Laravel API 接收来自 Postman 的 JSON 响应
- html - 单击 understrap 主题上的内容区域时显示不必要的边框