I am trying to filter an array of objects based on user input.
I wish filter based on the values of certain keys within the object. However, not all the objects have all keys inside them. This means when I check it throws an error.
How do I ignore if a particular object does not have one of the keys inside it and continues to output the matching objects?
Here is some sample data.
const data = [
{
name: "John Miller",
age: 33,
location: "Chicago",
address: '1 help street'
},
{
name: "Jane Doe",
age: 78,
address: '1 help me please lane'
},
{
name: "Jamie Stevens",
location: "San Diego",
age: 32
}
]
The second object does not have 'location' as a key and the third object does not have 'address' as a key.
const handleSearch = (query) => {
const keys = ['name', 'location', 'address']
const filter = data.filter((row) => (
keys.some((key) => (row[key].toLowerCase().includes(query))
)))
setFilteredData(filter)
}
Thank you,
CodePudding user response:
You can combine optional chaining with the nullish coalescing operator:
const handleSearch = (query) => {
const keys = ['name', 'location', 'address']
const filter = data.filter((row) => (
keys.some((key) => {
const k = row?.[key] ?? ''
return (k.toLowerCase().includes(query))
}
)))
setFilteredData(filter)
}
CodePudding user response:
Use the optional chaining operator(?.) and you also need to lower case the query:
const data = [
{
name: "John Miller",
age: 33,
location: "Chicago",
address: "1 help street",
},
{
name: "Jane Doe",
age: 78,
address: "1 help me please lane",
},
{
name: "Jamie Stevens",
location: "San Diego",
age: 32,
},
];
const handleSearch = (query) => {
const keys = ["name", "location", "address"];
const filtered = data.filter((row) =>
keys.some((key) => {
return row[key]?.toLowerCase().includes(query.toLowerCase())})
);
console.log(filtered);
};
handleSearch("Chicago")