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,