我正在使用javascriptincludes()
方法来过滤一个对象数组,看起来像这样;
const names = [
{name: 'Rose-mary Thompson', age: 30},
{name: 'Rose mary Samuel', age: 30},
{name: 'John-Doe Jackson', age: 30},
{name: 'John Doe Philips', age: 30},
]
如果我搜索"玫瑰玛丽",我希望结果也包括"玫瑰玛丽"。我不希望用户在搜索结果中出现带有-的名称前键入连字符(-)。
这是我的代码;
let searchQuery = 'Rose mary'
let filteredResults = []
const searchItems = () => {
if (searchQuery.length > 1) {
const results = names.filter((name) => {
return name.name.toLowerCase().includes(searchQuery.toLowerCase());
});
filteredResults = results
}
}
请问我怎么做到这一点?
includes
只会找到精确的匹配。由于您已经在搜索时调整了每个字符串,因此您可以"规范化"。searchQuery
和name
均为小写,-
转换为空格:
const searchItems = () => {
if (searchQuery.length > 1) {
const adjustedQuery = searchQuery.toLowerCase().replace(/-/g, " ");
const results = names.filter((name) => {
return name.name
.toLowerCase()
.replace(/-/g, " ")
.includes(adjustedQuery);
});
filteredResults = results;
}
};
const names = [
{ name: "Rose-mary Thompson", age: 30 },
{ name: "Rose mary Samuel", age: 30 },
{ name: "John-Doe Jackson", age: 30 },
{ name: "John Doe Philips", age: 30 },
];
let searchQuery = "Rose mary";
let filteredResults = [];
const searchItems = () => {
if (searchQuery.length > 1) {
const adjustedQuery = searchQuery.toLowerCase().replace(/-/g, " ");
const results = names.filter((name) => {
return name.name
.toLowerCase()
.replace(/-/g, " ")
.includes(adjustedQuery);
});
filteredResults = results;
}
};
searchItems();
console.log(filteredResults);
旁注:我也会使names
和searchQuery
参数到函数,并让它返回结果:
const names = [
{ name: "Rose-mary Thompson", age: 30 },
{ name: "Rose mary Samuel", age: 30 },
{ name: "John-Doe Jackson", age: 30 },
{ name: "John Doe Philips", age: 30 },
];
const searchItems = (names, searchQuery) => {
if (searchQuery.length > 1) {
const adjustedQuery = searchQuery.toLowerCase().replace(/-/g, " ");
const results = names.filter((name) => {
return name.name
.toLowerCase()
.replace(/-/g, " ")
.includes(adjustedQuery);
});
return results;
}
return names; // Or whatever you want when there's no query
};
console.log(searchItems(names, "Rose mary"));