在json中过滤并使用另一个json进行响应

时间:2014-12-17 22:18:03

标签: javascript jquery json filter livesearch

我需要像这样过滤一个JSON:

{
    "suggestions":[
      "futebol brasileiro",
      "futebol americano",
      "futebol",
      "musica",
      "musicas",
      "musica inedita de raul",
      "politica entre dilma e aecio",
      "politica",
      "politica macroeconomica"
   ]
}

当我输入" pol"在输入字段中,我需要获取此JSON:

{
    "suggestions":[
      "politica entre dilma e aecio",
      "politica",
      "politica macroeconomica"
   ]
}

我怎样才能使用纯Javascript?

我在JQuery中做到了这一点:

var url = "/busca/suggests/?q="+query;
$.getJSON(url, function (data) {
    for(var i=0; i < data.length; i++) {
       people[i] = accent_fold(data[i]);
    }
});

//Case insensitive search for our people array
var results = $.grep(people, function(item){
     return item.search(RegExp(query, "i")) != -1;
});

1 个答案:

答案 0 :(得分:1)

如果你可以使用ECMAScript 5 ......

否则: Polyfill for Array.prototype.filter()

(function() {
  var base = {
    "suggestions": [
      "futebol brasileiro",
      "futebol americano",
      "futebol",
      "musica",
      "musicas",
      "musica inedita de raul",
      "politica entre dilma e aecio",
      "politica",
      "politica macroeconomica"
    ]
  };

  var myResults = {};
  var txtBox = document.getElementById("search");
  var myDisplay = document.getElementById("displayResults");
  txtBox.onkeyup = getResults;

  function getResults() {
    var myInput = txtBox.value;
    myDisplay.innerHTML = "";
    var re = new RegExp(myInput, "gi");
    myResults.suggestions = base.suggestions.filter(function(ele) {
      return ele.search(re) != -1;
    });

    if (myResults.suggestions != "") {
      myDisplay.innerHTML = JSON.stringify(myResults);
    }
  }

})();
#displayResults {
  margin-top: 20px;
}
#displayResults {
  font-family: sans-serif;
}
<input type="text" id="search" placeholder="Type your search" />
<div id="displayResults"></div>