简体   繁体   English

部分字符串搜索javascript对象的指针

[英]Partially string search array of javascript objects for a needle

Using the following 使用以下

haystack = [{'id':'73','name':'Elvis'},{'id':'45','name':'Beatles'}, etc.]

I want to perform a search whereby I can find Elvis by searching for "elv" or "Elv" (thus, a case insensitive search). 我想执行搜索,以便通过搜索“ elv”或“ Elv”来找到猫王(因此,不区分大小写的搜索)。 Results should return in array thus allowing more than one needle to be returned from my search. 结果应该以阵列形式返回,这样就可以从我的搜索中返回一根以上的针。

My solution is convert my needle into lowercase, no spaces, and use a for loop to go thru my haystack making checks on a lowercase/nospace name. 我的解决方案是将我的指针转换为小写字母,没有空格,并使用for循环遍历我的干草堆,以检查小写字母/无空格的名称。 But I suspect there are other more resource friendly methods (I want to know if there is a better way so I can enhance my skillset/knowledge) 但是我怀疑还有其他更资源友好的方法(我想知道是否有更好的方法,这样我可以提高自己的技能/知识)

I had thought of using jQuery grep or inArray but both appear to be strict with their comparison. 我曾考虑过使用jQuery grep或inArray,但两者的比较似乎都很严格。 And array.filter() was another idea. 而array.filter()是另一个想法。 But various attempts so far fail. 但是到目前为止,各种尝试都失败了。

Thanks 谢谢

Not sure what you tried but .filter() should have worked. 不确定您尝试了什么,但是.filter()应该可以工作。 Make sure to lowercase both the search string and the name of the searched items. 确保同时将搜索字符串和搜索项目的name都小写。

var searchTerm = 'Elv'.toLowerCase();
var results = haystack.filter(function(item){
    return item.name.toLowerCase().indexOf(searchTerm) > -1;
});

alternatively you could use regexp for the comparison 或者,您可以使用regexp进行比较

var searchTerm = 'Elv',
    search = new RegExp(searchTerm, 'gi');

var results = haystack.filter(function(item){
    return item.name.match(search);
});

You can do it with Array#filter and some String's functions 您可以使用Array#filter和一些String的函数来完成此操作

var haystack = [{ 'id': '73', 'name': 'Elvis' }, { 'id': '45', 'name': 'Beatles' }];

var w = 'elv';

function search(word) {
    return haystack.filter(function(e) {
        return e.name.toLowerCase().substr(0, word.length) == word;
    });
}

console.log(search(w));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM