I am using .js and lodash
I need to be able to perform a deep search (depth and keys might vary) in objects. For example:
This is my data set which I need to perform the search:
const data = [
object1: {
key1: {
level1: {
filter: "this is a value"
},
junk: "..."
},
key2: {
level1:{
filter: ".."
}
junk: "this is complicated"
},
...
},
object2: { ... },
object3: { ... }
]
This is my search criteria which includes some properties of the objects in the dataset, and if the value is true I will use that as a filter to filter out the data
const searchCriteria = {
key1: {
level1: {
filter: true,
someOherFilter: false
}
},
key2: {
junk: true
},
...
}
So as you see I cannot depend of the name of the keys, I just have to retrieve all the "true" values from the search criteria, use them as chained filter and search the data set, when they match I return the whole object.
I can find the true values from the searchCriteria using:
const selectedFilters = _.keys(_.pickBy(filter, _.identity))
just need to apply the filters to the objects
Now I am left with an array that has the filters:
[filter] or [junk]
We are using lodash, I played quite a bit with plucks, and maps, and filters, and finds.. but couldn't get what I needed.
So assuming I get my search criteria as: ["key1", "level1", "filter]
or I might get it as ["key2", "junk"]
.
What's the best way to write the deep search function, preferably using lodash?