Skip to content

Instantly share code, notes, and snippets.

@TrevorJTClarke
Created May 8, 2015 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TrevorJTClarke/10a4d51f10eeb16ea8e5 to your computer and use it in GitHub Desktop.
Save TrevorJTClarke/10a4d51f10eeb16ea8e5 to your computer and use it in GitHub Desktop.
Easier setup for deep object based filtering on an array in angularjs. Use: ng-repeat="item in someArray | objectFilter:filterReqObject"
// I wanted to be able to simply change an object with key/search values, so that any array item keys that match also check for those search values
// The returned data, is only data that meets all requirements inside of the filterObject
//
// Example filterObject:{
// names: "Trevor",
// countries: "USA"
// }
// Example Array: [{
// title: "People in USA"
// names: ["Trevor", "Steve"]
// countries: ["USA"]
// },{
// title: "People in the world"
// names: ["John", "Steve"]
// countries: ["EU","USA"]
// }]
App.filter('objectFilter', [function($filter) {
return function(inputArray, filterObject){
if(!angular.isDefined(filterObject) || filterObject === ''){
return inputArray;
}
// assume the item has all filters until proven false
function hasAllFilters ( item ){
for(var meta in filterObject){
if(item[meta].indexOf(filterObject[meta]) === -1){
return false;
}
}
return true;
}
// setup only data that meets all requirements
var data = [];
angular.forEach(inputArray, function(item){
if(hasAllFilters(item)){
data.push(item);
}
});
return data;
};
}]);
@jaydeepmundrisoft
Copy link

H2o

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment