I have an object of folders/files that looks like this:
{
about.html : {
path : './about.html'
},
about2.html : {
path : './about2.html'
},
about3.html : {
path : './about3.html'
},
folderName : {
path : './folderName',
children : {
sub-child.html : {
path : 'folderName/sub-child.html'
}
}
}
}
And it can go 6-7 levels deep of folders having children.
I want to find the object where path is equal to a string that I provide. Regardless of how deep it is.
I'm using underscore which only does top level:
_.findWhere(files,{path:'./about2.html'}
How can I do a deep, nested search. Does underscore have something for this or do I need to build a mixin with recursion?
Though accepted answer works, it's too generic - it searches all the properties of an object to find children. I am proposing introducing an extra parameter, called 'recursProperty' which will be considered to go deep in the object. This solution is also setup to be used as lodash/underscore mixin and extends loadash/underscore capabilities.
It can be used as any other underscore function. e.g,
Not providing proper value for 'recursProperty' argument or providing null/undefined will simply make the search only on first level (no going deep).
This already has an accepted answer, but this other answer was very clean and perfect for my similar situation: https://stackoverflow.com/a/21600748/1913975
_.filter
+_.where
Instead of
findWhere
, usefilter
, which takes a function as the predicate rather than a key-value map. Use a recursive function to check the current node and possible children. Something like this:Edit
Assuming this works, you'll probably want to make a function
getRecursiveFilter(searchText)
. Here's how that would look:Note that here,
recursiveFilter
usesarguments.callee
to call itself recursively.Here's a working demo.
This isn't the prettiest code, but I tested it out and it seems to work the way you are asking. It's setup as a lodash/underscore mixin, but can be used however. Usage would be like this:
Implementation: