简体   繁体   中英

filter in a json and response with another json

I need to filter a JSON like this:

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

When I type "pol" in a input field, I need to get this JSON:

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

How can I do that using pure Javascript?

I did that in 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;
});

If you can use ECMAScript 5...

Otherwise: 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM