I have this array:
[
{
"label": "Group A",
"fields": [
{
"value": "color1",
"name": "Mike"
},
{
"value": "color2",
"name": "Mark"
}
]
},
{
"label": "Group B",
"fields": [
{
"value": "red",
"name": "Steve"
},
{
"value": "priority",
"name": "Laura"
}
]
},
{
"label": "Group C",
"fields": [
{
"value": "red",
"name": "Paul"
},
{
"value": "priority",
"name": "Mike"
}
]
}
]
and I’m using an input field to filter people by their name. So far I can only filter by "Group" by doing this:
post.label.includes(e.target.value)
but I’m having a hard time filtering by people’s names. The filtering is happening inside SearchBar component
For example, if the user enters "Mike" I should only see the groups with that user. Like this:
Group A
Mike
Group C
Mike
Here’s a LIVE DEMO. Thanks a lot in advance!
const handleSearchChange = (e: any) => {
if (!e.target.value) return setSearchResults(posts)
const resultsArray = posts?.filter((post: any)=> {
// return post.label.includes(e.target.value)
const result = post.fields.filter((field: any, idx: any) => {
return field.name.includes(e.target.value)
})
return result
})
setSearchResults(resultsArray)
}
3
Answers
You will need to loop through each fields inside the post array to find people with their name, here is a naive implementation:
and your
handleSearchChange
function should be like thisI have taken a look at the live demo and seen the issue. Here are the things to change in order to achieve what you want.
First create an
hanldeChange
function inApp.tsx
which would be passed to theSearchBar
component. The content of this would beThis would be passed to the
SearchBar
componentNote that
post
andsetSearchResults
are no longer needed.Refactor the
SearchBar
component to look like thisEverything should be fine after you do this. Note that there are cleaner ways of achieving this and this solution is based on the demo sample.
I think this is what you looking for.
We need to process each group and its people’s names individually. So, instead of using filter, we use map to iterate through each group. Then we filter the people’s Names within each group.