function loadJson(filter){
$.ajax({
type: 'GET',
url: 'http://path/to/example.json',
dataType: 'json',
cache: false,
beforeSend: function(){
console.log('loading');
},
success: function(response){
var filteredJson = $(response).filter(function (i,n) {
console.log('type ' + n.type);
var type = n.type.split(',');
for(var i=0; i<type.length;i++){
return n.type === filter;
}
});
console.log('parsing...' + filteredJson[0].name);
//console.log('filter by json ' + filteredJson);
for (var key in filteredJson){
if(filteredJson.hasOwnProperty(key)){
console.log('list ' + filteredJson[0].name);
}
}
$('#accordion').html(details).fadeIn();
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('XHR ' + jqXHR);
console.log('status ' + textStatus);
console.log('error ' + errorThrown);
},
complete: function(){
console.log('finished all tasks');
}
})
}
$('.filter a').on('click', function(e){
e.preventDefault();
console.log($(this).attr('id'));
loadJson($(this).attr('id'));
});
JSON
var JSONObject = [
{
"name": "A",
"type": "zoologist, hobbyist"
},
{
"name": "B",
"type": "judge, hobbyist"
},
{
"name": "C",
"type": "hobbyist"
}
];
如您所见,json:type中有1个以上。试图拆分内部类型filterJson,以便可以筛选所有类型并打印出名称。
如何溢出要处理的所有要过滤的类型?
答案 0 :(得分:1)
在您的示例中,我认为您正在寻找类似的内容:
var filteredJson = $(response).filter(function (i, n) {
return n.type && n.type.indexOf(filter) != -1;
});
即:如果变量&#34;过滤&#34;可以在任何&#34;类型&#34;中找到,然后按它过滤。
要进行测试,您可以这样做:
$.each(filteredJson, function () {
console.log('Filtered list: ' + this.name);
});
此处示例:http://jsfiddle.net/vo1t6znn/3/或以下SO-snippet ..
var varData = [{
"name": "A",
"type": "zoologist, hobbyist"
}, {
"name": "B",
"type": "judge, hobbyist"
}, {
"name": "C",
"type": "hobbyist"
}];
var filter = '';
$(document).on('change', '#filter', function() {
filter = $(this).val();
var filteredObj = $(varData).filter(function(i, n) {
return n.type && n.type.indexOf(filter) != -1;
});
var output = 'Result after filter: ';
$.each(filteredObj, function(k, v) {
console.log('list: ' + this.name);
output += this.name + ', ';
});
$('#result').html(output);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Filter:
<select id="filter" name="filter">
<option value="zoologist">zoologist</option>
<option value="hobbyist">hobbyist</option>
<option value="judge">judge</option>
</select>
<div id="result">Change filter to start</div>
&#13;