I have a search bar where you type employee name and it should return the name based on a filter. I have a nested JSON object (as shown below) where I need to drill into the object to access the employee's names in the array.
You can see the multiple options I tried to implement (they are commented out)
My problem is the code is not filtering the names and returning all the names not the names searched for. I get this error TypeError: Cannot read property 'filter' of undefined
The following code works to access the employee names in another component:
{test.map((result) => (result.details.map((innerArr) =>
<h5>{innerArr.employee}</h5>
)))}
how can I implement the above in the below code
const SearchByEmpComp = () => {
const [company, setCompany] = useState([
{
"company": "HIJ",
"_id": "610aeaec618ac5902c466541",
"details":
[
{
"employee": "Lesley Peden",
"notes": "Lesley's note",
"_id": "610aeaec618ac5902c466542"
},
{
"employee": "Wayne Smith",
"notes": "Wayne's note",
"_id": "610aeaec618ac5902c466543"
}
],
},
{
"company": "ABC",
"_id": "61003ff8e7684b709cf10da6",
"details":
[
{
"employee": "David Barton",
"notes": "some note!!",
"_id": "610aebb2618ac5902c46654e"
}
],
}
]);
//below code does not work
//attemp 1
const test = company.filter((r) =>
r.details.map((innerArr) => {
return innerArr.employee.toLowerCase().includes
(searchField.toLowerCase());
})
);
//attemp 1
// const test = company.map((el) => {
// return {...element, detail: element.detail.filter((details) =>
// details.employee.toLowerCase().includes
// (searchField.toLowerCase()))}
// })
//attemp 2
// const test = company.filter((res) => {
// return res.details.map((innerArr) =>
// innerArr.employee.toLowerCase().includes
// (searchField.toLowerCase()));
// });
//attemp 3
// const test = company.filter((comp) =>
// comp.details.employee.toLowerCase().includes(searchField.toLowerCase())
// );
const deatils = () => {
if (searchShow)
return <EmpDetailsByName test={test} />
}
};
return (
<>
<FormControl
type="search"
placeholder="Type Customer Name Here"
/>
<div>
<Button
onClick={handleClick}
>
Enter
</Button>
<div>{deatils()}</div>
</div
);
};
code to render names
const EmpDetailsByName = ({ test }) => {
return (
<>
{test.map((result) =>
(result.details.map((innerArr) =>
<h5>{innerArr.employee}</h5>
)))}
</>
);
};
export default EmpDetailsByName;