首页 > 解决方案 > 创建一个可以在对象数组中搜索元素的函数?

问题描述

我有这个对象数组:

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"}
];

我必须创建一个函数,在其中写下一个名称,该函数可以告诉你它是否是对象数组的一部分。有人可以帮助我吗?

标签: javascriptarraysfunctionobjectarrayobject

解决方案


此函数将返回与传递的参数(搜索字符串)匹配firstName或匹配的对象:lastNameinput

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>


推荐阅读