我有一个由构造函数创建的对象数组。这些对象有比这个例子更多的键值对。但是它们都很好地运作,所以不相关。让我们尝试简洁明了:
示例数组:
在 HTML 中,我有一个搜索字段
该字段的内容被修剪并复制到一个字符串数组中,由一个或多个空格分隔。
没问题。接下来,我想找到并返回
当
版本2返回的结果与版本1完全相同,只是它适用于比代码中列出的更多的键值对。太好了!但是当$input数组有多个值时,第二个值仍然被忽略。经过许多尝试和错误,我希望有人能指出我的错误。
这是版本3:(甚至可能是33):)
预期结果:目标是拥有与 $input 中任何字符串匹配的所有联系人。
非常感谢您提供的任何提示和见解!
示例数组:
let contactsArr = [
{id: 1, firstName: "Lucas", email: "lucas@fake.com"},
{id: 2, firstName: "Adrian", email: "adrian@fake.com"},
{id: 3, firstName: "Betrand", email: "zorro@fake.com"}
}
];
在 HTML 中,我有一个搜索字段
#search
。你猜对了。这个字段旨在搜索联系对象数组中的任何匹配值。该字段的内容被修剪并复制到一个字符串数组中,由一个或多个空格分隔。
const $input = $("#search").val().toLowerCase().trim().split(/[\s]+/);
没问题。接下来,我想找到并返回
contactsArr
内与$input
中的字符串相等(或包含部分)的对象的任何值。首先版本,我想出了这段代码:const filteredArr = contactsArr.filter(contact => {
return contact.firstName.toLowerCase().includes($input) ||
contact.email.toLowerCase().includes($input) ||
... // and more key-value pairs to check
});
当
$input
返回字符串或只有一个字符串的数组时,这很有效。如果数组包含多个字符串,则仅搜索并返回第一个字符串的结果。但这也有点混乱,因为对象在将来可能会有更多的键值对。因此,版本2如下所示:const filteredArr = contactsArr.filter(contact => {
return Object.values(contact).some(x => {
if (typeof x === "number") x = x.toString();
return x.toLowerCase().includes($input);
});
});
版本2返回的结果与版本1完全相同,只是它适用于比代码中列出的更多的键值对。太好了!但是当$input数组有多个值时,第二个值仍然被忽略。经过许多尝试和错误,我希望有人能指出我的错误。
这是版本3:(甚至可能是33):)
const filteredArr = contactsArr.filter(contact => {
return Object.values(contact).some(x => {
// contact.id number to string
if (typeof x === "number") x = x.toString();
// match with lowercase (same as $input)
x = x.toLocaleLowerCase();
// check if includes and return true or false
return $input.some(word => x.includes(word));
});
});
预期结果:目标是拥有与 $input 中任何字符串匹配的所有联系人。
非常感谢您提供的任何提示和见解!