reactjs 使用.filter和.some搜索嵌套对象

9udxz4iz  于 2023-03-29  发布在  React
关注(0)|答案(3)|浏览(157)

我有1级嵌套对象。
e.g.教师和学生。查询保存在搜索栏中输入的值。我试图过滤数组,但似乎不起作用。我缺少一些基本的东西,但不能数字

const studentunderT = [
  {
    id: 1,
    therapist_FName: 'Wonder',
    therapist_LName: 'Women',
    students: [
      { id: 1, student_LName: 'Test', student_Initial: 'BT1' },
      { id: 2, student_LName: 'Test', student_Initial: 'AL' },
    ],
  },
];
{
        studentunderT.filter(post => {
          if (query === '') {
            return post;
        } else if (post.students.some(std=>(
            std.student_Initial.toLowerCase().includes(query.toLowerCase())))) 
        {
          return post;
        }
        }).map((thr) => (
        <>
        {thr.students.map((stu) => (
            <Avatar color="red" key={thr.id} component={Link} to="/complete">{stu.student_Initial}
            </Avatar>
        ))
        }
qoefvg9y

qoefvg9y1#

如果要单独过滤所有学生,可以先用Array#flatMap创建一个扁平数组,然后再应用过滤器。

studentunderT.flatMap(x => x.students)
    .filter(s => s.student_Initial.toLowerCase().includes(query.toLowerCase()))
    .map(s => {/* return your JSX for each student */})
e37o9pze

e37o9pze2#

正如上面的注解中提到的,传递给Array.prototype.filter()的回调必须返回一个布尔值(true保留,false丢弃)。您的回调可能返回一个对象或undefined
听起来你想要这样的东西。。

const queryResults = useMemo(() => {
  if (query.trim().length === 0) {
    return studentunderT;
  }
  const normalisedQuery = query.trim().toLowerCase();
  return studentunderT.filter(({ students }) =>
    students.some(({ student_Initial }) =>
      student_Initial.toLowerCase().includes(normalisedQuery)
    )
  );
}, [studentunderT, query]);

然后你就可以在JSX中使用记忆体化的过滤数组了

{queryResults.flatMap(({ students }) =>
  students.map((stu) => (
    <Avatar color="red" key={stu.id} component={Link} to="/complete">
      {stu.student_Initial}
    </Avatar>
  ))
)}

注意,我使用学生id作为Avatar组件的key;教师ID对于每个学生将不是唯一的。

gpfsuwkq

gpfsuwkq3#

如果您喜欢用动态值声明一个变量filteredStudents,然后在JSX中Map这个filtered-students数组。
注意:正如您在评论中提到的,我使用了'B'作为query的值。

const query = 'B';
const studentunderT = [
  {
    id: 1,
    therapist_FName: 'Wonder',
    therapist_LName: 'Women',
    students: [
      { id: 1, student_LName: 'Test', student_Initial: 'BT1' },
      { id: 2, student_LName: 'Test', student_Initial: 'AL' },
    ],
  },
];
const filteredStudents = studentunderT.map(therapist => {
    if (query === '') {
     return therapist.students;
    }
    else {
     return therapist.students.filter(std => std.student_Initial
      .toLowerCase().includes(query.toLowerCase()));
    }
})
console.log('filteredStudents[0]:',filteredStudents[0]);

然后在JSX中:

filteredStudents[0].map(stu => (
 <Avatar color="red" key={stu.id} component={Link} to="/complete">{stu.student_Initial}
 </Avatar>
)

编辑2:如下面评论中的讨论,如果你有一个更复杂的功能,比如在 * 治疗师 * 之间选择,你可以做这个功能,比如[0]值是动态的而不是硬编码的:

filteredStudents[therapistID-1].map(stu => ( //...

注意:therapistID将是一个等于= therapistid的状态,然后在访问它时减去-1,因为数组是基于0的,这意味着它们从索引0开始,我怀疑你使用每个治疗师的递增id

相关问题