代码之家  ›  专栏  ›  技术社区  ›  bp123

将筛选器与includes一起使用不会筛选

  •  0
  • bp123  · 技术社区  · 6 年前

    我试着过滤掉一组 classes 在名为studentUserProfile的对象中。当我运行下面的代码时,filter不会过滤掉任何东西。

    对象 studentUserProfile ;

    {  
       "_id":"ZgfgbGpMxF5T6pNT8",
       "firstName":"Angela",
       "classes":[  
          {  
             "classId":"3x8cNzzr4DQ4PioM7"
          },
          {  
             "classId":"oehC4pWbFLDAjbzvt"
          }
       ]
    }
    

    filterIds = ["oehC4pWbFLDAjbzvt", "3x8cNzzr4DQ4PioM7"];

    代码

    let studentUserProfiles = this.props.studentUserProfiles.map((studentUserProfile) => {
      studentUserProfile.classes = studentUserProfile.classes.filter(myClass => filterIds.includes(myClass.classId));
      return studentUserProfile;
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   bp123    6 年前

    仅供参考-所以问题在于我是怎么回来的 studentUserProfile .

    const studentUserProfiles = this.props.studentUserProfiles.map((studentUserProfile) => {
      const classes = studentUserProfile.classes.filter(myClass => filterIds.includes(myClass.classId));
      if (classes.length >= 1) {
        return {
          ...studentUserProfile,
          classes,
        };
      }
      return null;
    }).filter(studentUserProfile => studentUserProfile !== null);