对象数组

时间:2015-06-17 12:43:06

标签: javascript jquery arrays full-text-search

我有以下示例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字段中搜索短语?例如,搜索短语another text使用indexOf无法工作,因为这两个单词并不紧挨着。什么是在jQuery中执行此搜索的有效方法?

2 个答案:

答案 0 :(得分:6)

如果你被卡住,你可以使用香草JS。它确实使用了filterevery,它们在旧版浏览器中不起作用,但有可用的填充。

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

答案 1 :(得分: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