I'm trying to come up with a function that allows for a deep generic search of an array of objects, even nested object data like this:
let orders = [
{
id: 7,
order_number: 1234
address: {
last_name: "Anderson",
first_name: "John"
}
},
{
id: 8,
order_number: 4321,
address: {
last_name: "Franko",
first_name: "Billy",
}
}
]
The function needs to be flexible enough to handle any String or Numeric data and search the entire array of objects without needed to know which fields to search for, should search the entire objects fields
So for example something like this would work:
let searchedData = searchData(orders, 'john')
Would return:
[
{
id: 7,
order_number: 1234
address: {
last_name: "Anderson",
first_name: "John"
}
}
]
And
let searchedData = searchData(orders, '4321')
Would return:
[
{
id: 8,
order_number: 4321,
address: {
last_name: "Franko",
first_name: "Billy",
}
}
]
This would need to be able to work to unlimited levels deep, the depth of the objects will not be known.
It also needs to be case insensitive.
I did the following function:
searchData(arr, query) {
let data = [];
for(let item of arr) {
if(item.order_number.includes(query) || item.address.last_name.toLowerCase().includes(query) || item.address.first_name.toLowerCase().includes(query)) {
data.push(item);
}
}
}
The problem is this function isn't abstract enough to work with any array of objects.