Reputation:
I have a table in that I am using a search bar I need to make a search to be generic for all fields if any of the value will get a match that result will show what I did I made just for one field but I need to make it for all field so I need to make like whatever value is present that all will get check like generic search like for example if I search using name, id, module, etc all that value will use for search bar
[{
"isConsole": true,
"taskStatus": "SUCCESS",
"taskName": "G-csv_download-25",
"id": 463,
"module": "Management",
"subModule": "Grid",
"taskId": "1fc0d5a7-834a-4906-8448-16835e8838b0",
"projectId": 42,
"createdAt": "2023-01-21T05:56:50.184965Z",
"size": 0.20800000000000002,
"failureMessage": null
}, {
"isConsole": true,
"taskStatus": "SUCCESS",
"taskName": "G-csv_download-26",
"id": 464,
"module": "Management",
"subModule": "Grid",
"taskId": "2724fcbf-d25b-424f",
"projectId": 42,
"createdAt": "2023-01-21T06:02:48.557536Z",
"size": 0.20800000000000002,
"failureMessage": null
}, {
"isConsole": true,
"taskStatus": "SUCCESS",
"taskName": "G-csv_download-27",
"id": 465,
"module": "Management",
"subModule": "Grid",
"taskId": "26642fb3-1593-4e0d-b276-901bb7e729c3",
"projectId": 42,
"createdAt": "2023-01-21T10:31:30.965508Z",
"size": 0.20800000000000002,
"failureMessage": null
}]
this is for single field
const searchBasedFilter = React.useMemo(
() =>
downloads.filter((data) =>
searchData
? data.subModule?.toLowerCase().includes(searchData?.toLowerCase())
: data
),
[searchData, downloads]
);
Upvotes: -1
Views: 228
Reputation: 584
To make the search generic for all fields, you can use the Object.values() method to extract all the values of the object, and then use Array.prototype.some() method to check if any of the values match the search query.
Something like:
const searchBasedFilter = React.useMemo(
() =>
downloads.filter((data) =>
searchData
? Object.values(data).some((value) =>
value?.toString().toLowerCase().includes(searchData?.toLowerCase())
)
: data
),
[searchData, downloads]
);
This will check all the values of the object, whether it is a string or number, and will check if the search query is present in any of the values of the object.
Upvotes: 1