首页 > 解决方案 > 将过滤器与包含一起使用不会过滤

问题描述

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

对象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;
});

标签: javascriptreactjsecmascript-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);

推荐阅读