Egidi
Egidi

Reputation: 1776

Filtering subarray of objects

I need to filter a subarray of elements.

var university = {
    "fax": "123345",
    "email": "[email protected]",
    "url": "www.test.com",
    "classes": [
        {
            "number": "1",
            "name": "maths",
            "students": [
                {
                    "name": "Max",
                    "exams": [
                        {
                            "date": "2016-01-04T18:32:43.000Z",
                            "passed": false
                        },
                        {
                            "date": "2016-01-04T18:32:43.000Z",
                            "passed": true
                        },                       
                        {
                            "date": "2016-01-04T18:32:43.000Z",
                            "passed": false
                        },
                        {
                            "date": "2016-01-04T18:32:43.000Z",
                            "passed": true
                        }
                      ]
                },
                {...}
              ]
        },
        {...}
    ]
}

Ok I need to get all the classes without filtering, all the students of each class without filtering, but in the exams array I only need to get the ones that passed.

I tried the following:

university.classes.students.exams.filter(function (el) {
    return el.passed
});

But it is not working...

I've googled a solution to this without success...any help would be appreciated.

Upvotes: 0

Views: 1062

Answers (1)

tymeJV
tymeJV

Reputation: 104775

classes and students are arrays - so you have to loop those as well:

university.classes.forEach(function(uniClass) {
   uniClass.students.forEach(function(student) {
       student.exams = student.exams.filter(function (el) {
           return el.passed;
       });
   });
});

Upvotes: 4

Related Questions