我需要像这样过滤一个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;
});
如果你能使用 ECMAScript 5
...否则:用于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>