Various JSON filter types
Looking at JSON and filtering out unwanted data with various methods. EACH / GREP and REMOVE
by Andrew Pougher
HTML
<div id="months"></div>
<hr>
<div id="names"></div>
<hr>
<div id="countries"></div>
JavaScript
$(document). ready(function() {
countries= [
{'id':'XX','name':'Afghanistan'},
{'id':'AF','name':'Afghanistan'},
{'id':'AL','name':'Albania'},
{'id':'DZ','name':'Algeria'},
{'id':'CH','name':'Suisse'},
{'id':'OZ','name':'Down Under'}
];//r
var arr = [
{ 'name': "robin", 'age': 19 },
{ 'name': "tom", 'age': 29 },
{ 'name': "tom", 'age': 29 },
{ 'name': "tom", 'age': 29 },
{ 'name': "test", 'age': 39 }
];
var months = [
{'tripstartdate':'January'},
{'tripstartdate':'February'},
{'tripstartdate':'March'},
{'tripstartdate':'April'},
{'tripstartdate':'May'},
{'tripstartdate': 'June'},
{'tripstartdate':'July'},
{'tripstartdate':'August'},
{'tripstartdate':'September'},
{'tripstartdate':'October'},
{'tripstartdate':'November'},
{'tripstartdate': 'December'},
{'tripenddate': 'January'},
{'tripenddate': 'December'}];
// grep METHOD
months = $.grep(months, function(value, i) {
var f = value['tripstartdate'];
var r = value['tripenddate'];
return (f !== "April" && f !== "May" && f !== "December" && r !== "December");
});
$('#months').html( JSON.stringify(months));
// ONE METHOD
Array.prototype.remove = function(name, value) {
var rest = $.grep(this, function(item){
return (item[name] !== value); // <- You may or may not want strict equality
});
this.length = 0;
this.push.apply(this, rest);
return this;
};
arr.remove("name", "test");
arr.remove("name", "tom");
$('#names').html(JSON.stringify(arr))
// TWO METHOD IFFY
$.each(countries, function(i, result) {
if( result.id == 'XX' ) {
//if anything else not equal XX
return true
}else if (result.id == 'AF'){
return true
}else{
// otherwise...