byrdr
byrdr

Reputation: 5487

Angular filtering JSON objects of objects

I've ran into an issue trying to filter my data based on the routeparam. I believe it might be because of the way my JSON is constructed. From what I can tell angular is not able to filter objects or objects. Is there a custom filter for this? Here is the page I'm working with http://secret-hollows-7338.herokuapp.com/events

I have my JSON here

'year': {    
'August': [
    {
      'day':'9', 
      'title':'Dave Ramsey\'s Financial Peace University', 
      'summary': 'Financial Peace University (FPU) is a biblically-based, life-changing program that teaches people how to make wise decisions with money. You will be empowered with the practical skills and confidence needed...', 
      'decription': 'cal desc'
    },
    {
      'day':'17', 
      'title':'Divorce & Beyond Seminar', 
      'summary': 'If you are separated from your spouse, going through a divorce or are divorced, we encourage you to seek support. We understand the feelings of guilt, rejection, fear, confusion, isolation,...', 
      'decription': 'cal desc two'
    },
          ],
  'September': [
    {
      'day':'9 sep', 
      'title':'sep title', 
      'summary': 'sep summ', 
      'decription': 'sep desc'
    }
          ]
}

my filter logic for the route params (I'm passing the Key in as the routeparam)

$scope.month={};
$scope.month=$routeParams.id; 

my view logic

 <div class="events" ng-repeat="cal in calendar[0].year">
  <div ng-repeat="(val, key) in cal">
      <a href="/events/{{key.day}}">
        <article class="eventslist">
           <div class="numberedDate">
             <h3>{{key.day}}</h3>
            </div>
            <div class="calInfo">
               <h5>{{key.title}}</h5>
               <p>{{key.summary}}&nbsp;<a>more</p>
             </div>
          </article>
      </a>
  </div>

I'd like to use this as my filter, but it doesn't work for some reason.

<div class="calendar" ng-repeat="cal in calendar[0].year | filter:month">

Upvotes: 0

Views: 1012

Answers (1)

runTarm
runTarm

Reputation: 11547

The filter filter does not support filtering over an object.

Your calendar[0].year is an object, not array, and seems like you would like to filter by its keys.

If that's the case, you could write a custom filter like this:

appModule.filter('filterKey', function() {
  function comparator(a, b) {
    return (''+a).toLowerCase().indexOf((''+b).toLowerCase()) > -1;
  }

  return function(obj, searchKey) {
    var filtered = {};
    angular.forEach(obj, function(value, key) {
      if (comparator(key, searchKey)) {
        filtered[key] = value;
      }
    });
    return filtered;
  };
})

and in ng-repeat:

<div class="calendar" ng-repeat="(key, val) in calendar[0].year | filterKey:month">

Hope this helps.

Upvotes: 1

Related Questions