将过滤器与包含一起使用不会过滤

时间:2018-07-17 04:12:56

标签: javascript reactjs ecmascript-6

我正在尝试过滤出名为StudentUserProfile的对象中classes的对象数组。当我运行下面的代码时,过滤器不会过滤掉任何内容。

对象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 个答案:

答案 0 :(得分:0)

仅供参考-因此问题在于我返回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);