多个搜索功能通过数组

时间:2017-06-27 15:41:44

标签: javascript

我正在尝试搜索多个值的列表。

以下是值的示例:

[
    {
    "color":"blue",
    "medium":"Sculpture",
    "place":"Garage"
    }
    {
    "color":"red",
    "medium":"Painting",
    "place":"Pool"
    }
]

以下是我的代码。非常适合找到单个值。但我需要找到多个值。例如,我需要查看并查找查询结果,例如:“red blue”或“blue painting”。

它应该返回包含两个单词的结果。

我真的不知道如何解决这个问题,有人有想法吗? 非常感谢

function search(){
    var search = $('#search').val();
    if(search.length < 1) {
      return null;
    };

    var searches = search.split(" ");
    var fields = ["color","medium","place"]; 
    var results = [];

    $.each(searches, function(i, word){
      var wordResult = searchInJson(word,fields,json);
      if( wordResult.length > 0 ) {
        results.push(wordResult);
      }
    });

    var results = searchInJson(searches,fields,json);
    displaySearchResults(results);
};

function searchInJson(search,fields,json) {
    var regex = new RegExp(search);
    var results = [];
    $.each(json, function(i, image){
      $.each(fields, function(j, fieldname){

        var field = image[fieldname];
        if (regex.test(field)) {
          results.push( image );
        }
      });
    });
    return results;
}

1 个答案:

答案 0 :(得分:0)

这是一种快速尝试的方法:

var list = [
    {
    "color":"blue",
    "medium":"Sculpture",
    "place":"Garage"
    },
    {
    "color":"red",
    "medium":"Painting",
    "place":"Pool"
    }
];

var search = "red painting";

var results = list.filter(function (el) {
  var s = search.toLowerCase().split(" ");
  for (var key in el) {
    for (var i=0; i < s.length; i++) {
      if (el[key].toLowerCase() == s[i]) {  // this could use indexOf depending on if you want to match partial words
        s.splice(i,1);
        i--;
        if (!s.length) return true;
      }
    }
  }
  return false;
});

console.log(results);