我有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>
))
}
3条答案
按热度按时间qoefvg9y1#
如果要单独过滤所有学生,可以先用
Array#flatMap
创建一个扁平数组,然后再应用过滤器。e37o9pze2#
正如上面的注解中提到的,传递给Array.prototype.filter()的回调必须返回一个布尔值(
true
保留,false
丢弃)。您的回调可能返回一个对象或undefined
。听起来你想要这样的东西。。
然后你就可以在JSX中使用记忆体化的过滤数组了
注意,我使用学生
id
作为Avatar
组件的key
;教师ID对于每个学生将不是唯一的。gpfsuwkq3#
如果您喜欢用动态值声明一个变量
filteredStudents
,然后在JSX中Map这个filtered-students数组。注意:正如您在评论中提到的,我使用了
'B'
作为query
的值。然后在JSX中:
编辑2:如下面评论中的讨论,如果你有一个更复杂的功能,比如在 * 治疗师 * 之间选择,你可以做这个功能,比如
[0]
值是动态的而不是硬编码的:注意:
therapistID
将是一个等于= therapist 的id
的状态,然后在访问它时减去-1
,因为数组是基于0的,这意味着它们从索引0
开始,我怀疑你使用每个治疗师的递增id
。