I've created a React live search dropdown component that filters an array of objects based on a search term. It currently filters the objects by title and displays all related objects, which is working well.
Current Implementation:
Data Structure
data: [
{ id: 1, title: 'Some title here' },
{ id: 2, title: 'Another title' },
{ id: 3, title: 'last title' },
]
Component
<LiveSearch
term={term}
data={data} />
Inside Live Search Component:
The data is filtered by the search term and a list is rendered accordingly.
return data
.filter(item => item.title.toLowerCase().includes(term.toLowerCase()))
.map((item, idx) => <li key={idx}>{item.title}</li>
I want to enhance my object search functionality by being able to pass an array of property names into my component for comparison with the search term.
My idea is to iterate through the object properties, break the loop if any match is found, and add that object to the display list.
Objective:
Data Structure
data: [
{ id: 1, country: 'Canada', title: 'Some title here' },
{ id: 2, country: 'Australia', title: 'Another title' },
{ id: 3, country: 'Netherlands', title: 'last title' },
]
Component
<LiveSearch
searchFields={['country', 'title']}
term={term}
data={data} />
Filtering inside the Component:
return data
.filter(item => {
// Dynamic filtering logic goes here
})
.map((item, idx) => <li key={idx}>{item.title}</li>
In my filtering process, I'm attempting to dynamically loop through the array and create similar logic to this:
item.searchFields[0].toLowerCase().includes(term.toLowerCase()) ||
item.searchFields[1].toLowerCase().includes(term.toLowerCase())
This approach allows for an infinite number of search fields/properties to be included in the search.