search: (query) => {
const websites = cloneDeep(this.state.websites);
let results = [];
websites.forEach(object => {
let isResult = false;
const searchIn = ["code", "link", "offline", "online"];
for(let prop = 0; prop < 4; prop++) {
if(isResult) break;
const propVal = object[searchIn[prop]];
if(typeof propVal === "string" && propVal !== "undefined") {
if(propVal.toLowerCase().indexOf(query.toLowerCase()) !== -1) {
isResult = true; }
}
}
if(isResult) results.push(object);
});
}
附注我有一组对象。我需要检查每个对象的四个属性中至少有一个是否匹配。 “查询”= 子字符串。
最佳答案
你在这里把事情复杂化了,通过使用 forEach
遍历对象,然后迭代所有 object
键来检查它是否是搜索到的属性之一并且它的值是否包含搜索到的 query
字符串。
顺便说一句,你的函数没有返回任何东西,因为你只是试图填充 results
数组而不返回它。
解决方案:
您可以简单地使用 Array#filter()
method 来过滤 websites
数组,您可以在其中使用 Array#some()
method 遍历 searchIn
属性数组 并检查每个 object
相关属性,以及它们的值是否包含搜索到的 query
字符串。
你的代码应该是这样的:
const searchIn = ["code", "link", "offline", "online"];
search: (query) => {
query = query.toLowerCase()
websites.filter(o => searchIn.some(k => o[k] && typeof o[k] === "string" && o[k].toLowerCase().indexOf(query) > -1));
}
关于javascript - 如何优化我的算法以使用子字符串进行搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52076981/