In a React Project, I have an array of objects where I am displaying the values based on certain conditions. I’m able to populate the data with one parameter but, I also want to display with other parameter. Please go through the code below.
const users = [
{ name: "Jack", id: "1" },
{ name: "Lisa", id: "2" },
{ name: "Peter", id: "3" },
{ name: "Roman", id: "4" },
{ name: "Sarah", id: "5" },
{ name: "Eric", id: "6" },
{ name: "Fiora", id: "7" },
];
const filterNames = ({ name }) => {
return name.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
};
As you can see I’m filtering the array data with “name” parameter which searches exactly as expected but, want to populate records with “id” parameter, like it should work for both “name” and “id”. Any appropraite solution highly appreciated.
Below is the stackblitz link for your reference
Stackblitz Link: https://stackblitz.com/edit/react-search-filter-demo-fmkhv2?file=index.js
2
Answers
You can modify the
filterNames
function to accept an additional parametersearchParameter
, which can be eithername
orid
. Then, check thesearchParameter
, if it isname
, filter the array based on thename
property, and if it isid
, filter the array based on theid
property:The filter callback can do anything you want it to do, as long as it returns a truthy value for elements you wish to include.