【问题标题】:Filtering subarray of objects过滤对象的子数组
【发布时间】:2016-05-02 04:38:33
【问题描述】:

我需要过滤一个元素的子数组。

var university = {
    "fax": "123345",
    "email": "test@test.com",
    "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
                        }
                      ]
                },
                {...}
              ]
        },
        {...}
    ]
}

好的,我需要得到所有不过滤的班级,每个班级的所有学生不过滤,但是在考试数组中我只需要得到通过的那些。

我尝试了以下方法:

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

但它不起作用......

我在谷歌上搜索了一个解决方案,但没有成功...任何帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays filter sub-array


    【解决方案1】:

    classesstudents 是数组 - 所以你也必须循环它们:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-11
      • 2021-03-13
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多