0

I want to filter the objects where the object structure is a little complex. I am looking a kind of deep filtering, where angular $filter works on the elements inside the array:

[
  {
    "schoolId": 12345,
    "schoolName": "ZXCVB",
    "classes": [
      {
        "classId": "C1",
        "students": 50
      },
      {
        "classId": "C2",
        "students": 100
      }
    ]
  },

  {
    "schoolId": 98765,
    "schoolName": "QWERTY",
    "classes": [
      {
        "classId": "C1",
        "students": 100
      },
      {
        "classId": "C2",
        "students": 50
      }
    ]
  }
]



(This is an array of schools. Each school has array of classes and classes has Ids)
Here the thing I am looking for help is how can I filter on classId, so that it returns me the school object.

2 Answers 2

1

You should use a custom filter, defining your own filter function. Example:

.filter('classFilter', [function () {
    return function (input, classId) {
        if(!classId) return input;
        var out = [];
        input.forEach(function(s) {
            s.classes.forEach(function(c){
            if(c.classId==classId) out.push(s);
          })
        });
        return out;
    };
}]);

Live: http://jsfiddle.net/87yod9bf/2/

Sign up to request clarification or add additional context in comments.

1 Comment

@Italo Ayres - Thanks! This is what I was looking for. The moment I asked this question I looked for implementing a custom filter. The one that I wrote is similar to this. Thanks again.
1

Can be done with filter and some:

function filterByClassId(schools, id){
    return schools.filter(function(school){
        return school.classes.some(function(c){
            return c.classId === id;
        });
    });
}

It's up to you if you want to set it up as a filter for angular.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.