I have 1 level nested object.
e.g. Teacher and Students. query hold the value entered in search bar. I am trying to filter the array but it does not seem to work. I am missing something basic but cant figure
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
Answers
As mentioned in the comments above, the callback passed to Array.prototype.filter() must return a Boolean value (
true
to keep,false
to discard). Yours potentially returns an object orundefined
.Sounds like you want something like this…
then you can use the memo-ised, filtered array in your JSX
Note I’ve used the student
id
as thekey
for yourAvatar
component; the teacher ID would not have been unique for each student.If you want to filter all the students separately, you can first create a flattened array with
Array#flatMap
before applying the filter.If you prefer to declare a variable of
filteredStudents
with a dynamic value and then inside your JSX just map over this filtered-students array.NOTE: I used value
'B'
forquery
as you mentioned in your comment.And then in your JSX:
EDIT2:
As in the discussion bellow in the comments, if you were to have a more complex functionality, such as choosing between therapists, you can do that functionality such as that the
[0]
value to be dynamic rather than hardcoded:NOTE:
therapistID
would be a state that equals to = therapist‘sid
, you then subtract-1
when accessing it, since arrays are 0-based meaning that they start at index0
and I suspect you to use incrementingid
‘s of each therapist.