filter in a json and response with another json

103 views Asked by At

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;
});
1

There are 1 answers

0
Mike Loffland On BEST ANSWER

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>