Given a search string:
Jane
and this array of objects:
[
{
name: 'Jane Smith',
address: '123 Main St, Boston, MA 01234',
telephone: {
primary: '1234567890',
secondary: '1112223333'
}
},
{
name: 'John Smith',
address: '333 Main St, New York, NY 56789',
telephone: {
primary: '2223334444',
secondary: '3334445555'
}
},
...
]
we can filter the array by name:
arr.filter(person => person.name.includes(search))
Great. That works well if all we are only searching by each object's name
property.
What is the best practice for filtering across all properties of an object?
Do we have to do something like:
arr.filter(person =>
person.name.includes(search) ||
person.address.includes(search) ||
person.telephone.primary.includes(search) ||
person.telephone.secondary.includes(search)
)
This becomes tedious and error prone if there are more than a couple properties.
Is there a way to filter an array if any property's value matches a search string?
Update:
This works nicely for top level properties on the person object.
.filter(person => {
for (let property in person) {
return String(person[property]).includes(search)
}
})
Working on trying to find a nice solution for recursively searching through properties that may themselves be objects.