簡體   English   中英

客戶端對對象數組進行全文搜索

[英]Client-side full-text search on array of 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);

使用jQuery的$.grep進行搜索可能很有效,例如針對單個單詞執行以下搜索:

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

但是,如何在對象的content字段中搜索短語? 例如,使用indexOf搜索短語another text將不起作用,因為兩個單詞並不相鄰。 在jQuery中執行此搜索的有效方法是什么?

如果遇到問題,可以使用Vanilla JS。 它確實使用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 

如果您使用query-js ,則可以這樣做

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

如果它至少應匹配一個,則將&&更改為|| truefalse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM