简体   繁体   English

客户端对对象数组进行全文搜索

[英]Client-side full-text search on array of objects

I have the following example JavaScript array of objects and need to enable users to search on it using words/phrases, returning the objects: 我有以下示例JavaScript对象数组,需要使用户能够使用单词/短语在其上进行搜索,并返回对象:

var items = [];
var obj = {
    index: 1,
    content: "This is a sample text to search."
};
items.push(obj);
obj = {
    index: 2,
    content: "Here's another sample text to search."
};
items.push(obj);

It's probably efficient to use jQuery's $.grep to perform the search, such as this for a single word: 使用jQuery的$.grep进行搜索可能很有效,例如针对单个单词执行以下搜索:

var keyword = "Here";
var results = $.grep(items, function (e) { 
    return e.content.indexOf(keyword) != -1; 
});

However, how do you search for a phrase in the content field of the objects? 但是,如何在对象的content字段中搜索短语? For example, searching for the phrase another text won't work using indexOf , because the two words aren't next to each other. 例如,使用indexOf搜索短语another text将不起作用,因为两个单词并不相邻。 What's an efficient way to perform this search in jQuery? 在jQuery中执行此搜索的有效方法是什么?

You can use vanilla JS if you're stuck. 如果遇到问题,可以使用Vanilla JS。 It does use filter and every which won't work in older browsers, but there are polyfills available. 它确实使用filter并且every filter都无法在较旧的浏览器中运行,但是可以使用polyfill。

 var items = []; var obj = { index: 1, content: "This is a sample text to search." }; items.push(obj); obj = { index: 2, content: "Here's another sample text to search." }; items.push(obj); function find(items, text) { text = text.split(' '); return items.filter(function(item) { return text.every(function(el) { return item.content.indexOf(el) > -1; }); }); } console.log(find(items, 'text')) // both objects console.log(find(items, 'another')) // object 2 console.log(find(items, 'another text')) // object 2 console.log(find(items, 'is text')) // object 1 

if you use query-js you can do this like so 如果您使用query-js ,则可以这样做

var words = phrase.split(' ');
items.where(function(e){
           return words.aggregate(function(state, w){ 
                    return state && e.content.indexOf(w) >= 0;
                  });
},true);

if it should just match at least one change the && to || 如果它至少应匹配一个,则将&&更改为|| and true to false truefalse

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

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