I'm trying to filter through an array and then a nested array within that array, in the same function.
It works fine while filtering through keysFirst and keysSecond.
The person array has two nested arrays: skills and roles. The skills array has an attribute of name and an attribute of stars. Here I want to filter on the name attribute.
How do I make a function where I'm able to filter through either keysFirst and/or keysSecond and also through one or both of the nested arrays?
Hope that makes sense.
Homepage.jsx
const [queryText, setQuery] = useState("");
const [querySecond, setQuerySecond] = useState("");
const [queryThird, setQueryThird] = useState("");
const keysFirst = ["firstname", "lastname"];
const keysSecond = ["location", "department"];
const keysThird = ["skills", "roles"];
const [data, setData] = useState([
{
firstname: "Brad",
lastname: "Pitt",
location: "America",
department: "Hollywood",
skills: [
{ name: "Actor", stars: 5 },
{ name: "Fighting", stars: 4 },
],
roles: [
{ name: "Snatch", salary: 1000 },
{ name: "Fightclub", salary: 2000 },
],
},
{
firstname: "Jason",
lastname: "Statham",
location: "England",
department: "Hollywood",
skills: [
{ name: "Driving", stars: 2 },
{ name: "Taxi", stars: 4 },
],
roles: [
{ name: "Crank", salary: 3000 },
{ name: "Transporter 2", salary: 4000 },
],
},
]);
const searchFunction = (data) => {
const personFiltered = data.filter(
(item) =>
keysFirst.some((keysFirst) =>
item[keysFirst].toLowerCase().includes(queryText.toLowerCase())
) &&
keysSecond.some((keysSecond) =>
item[keysSecond].toLowerCase().includes(querySecond.toLowerCase())
)
);
return personFiltered;
};