【问题标题】:Client-side full-text search on array of objects对象数组的客户端全文搜索
【发布时间】:2015-06-17 12:43:05
【问题描述】:

我有以下示例 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 中执行此搜索的有效方法是什么?

【问题讨论】:

  • :contains 怎么样?
  • 谢谢,@GuruprasadRao。 :contains 是否考虑到短语单词不必连续,但可以在文本中的任何位置?
  • 是的!查看this link了解更多详情

标签: javascript jquery arrays full-text-search


【解决方案1】:

如果遇到困难,可以使用原版 JS。它确实使用了 filterevery,这在旧版浏览器中无法使用,但有可用的 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(item => {
    return text.every(el => {
      return item.content.includes(el);
    });
  });
}

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

(编辑:更新为使用includes,以及略短的箭头函数语法)。

【讨论】:

    【解决方案2】:

    如果你使用query-js,你可以这样做

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

    如果它应该至少匹配一个,请将 && 更改为 ||true 更改为 false

    【讨论】:

    • 谢谢,@RuneFS。非常好。该链接要求我登录 Wordpress 博客。
    • GitHub 链接已损坏:github/runefs/query-js。哪里可以下载 JS 库?
    • 应该是github.com/runefs/query-js 或者你可以通过 npm install query-js 安装
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多