Reputation: 442
I am making a react project in which I'm using table and I need to add a search functionality to it. Right now the table is populated with objects.
function createData(Estimate, ServiceProvider, Vehicle, Date, Amount, Status, Action) {
return {Estimate, ServiceProvider, Vehicle, Date, Amount, Status, Action};
}
const rows = [
createData('#10001', "Euro Motors", "2010 Toyota Corolla CE FWD", "January 28, 2021", "$395.11", "Approved",),
createData('#10002', "Auto Motors", "Some car model", "January 28, 2021", "$395.11", "Pending"),
createData('#10003', "Some other Motors", "Some other car model", "January 28, 2021", "$395.11", "Approved"),
]
const [tableData, setTableData] = useState(rows)
Right now I have search functionality for just ServiceProvider using this
const requestSearch = (searchedVal) => {
const filteredRows = rows.filter((row) => {
return row.ServiceProvider.toLowerCase().includes(searchedVal.toLowerCase());
});
setTableData(filteredRows);
};
but I need it for Estimate, ServiceProvider, Vehicle. How can I extend the functionality to all three so whatever the user searches in the search bar it checks all three columns and filters out rows with repeation.
Upvotes: 2
Views: 528
Reputation: 9284
Just add the conditions for Estimate
, and Vehicle
and combine them using ||
operator within the requestSearch
function, like this:
return row.ServiceProvider.toLowerCase().includes(searchedVal.toLowerCase()) ||
row.Estimate.toLowerCase().includes(searchedVal.toLowerCase()) ||
row.Vehicle.toLowerCase().includes(searchedVal.toLowerCase())
Upvotes: 1
Reputation: 59
You can write a generic solution for all the keys without actually mentioning the keys individually. Try following code snippet:
const requestSearch = (searchedVal) => {
const filteredRows = rows.filter((row) => {
let found = Object.values(row).map(o => o.toLowerCase()).find(o => o.includes(searchedVal));
if(found) return true;
else return false;
});
console.log(filteredRows);
};
Note: this will work if all of your search values are string, for number you'll need to add some conditional handling to it.
Upvotes: 1