Monday, June 3, 2024
99
rated 0 times [  100] [ 1]  / answers: 1 / hits: 37334  / 11 Years ago, wed, july 10, 2013, 12:00:00

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?


More From » underscore.js

 Answers
16

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:



_.findDeep(testItem, { 'path': 'folderName/sub-child.html' })


Implementation:



findDeep: function(items, attrs) {

function match(value) {
for (var key in attrs) {
if(!_.isUndefined(value)) {
if (attrs[key] !== value[key]) {
return false;
}
}
}

return true;
}

function traverse(value) {
var result;

_.forEach(value, function (val) {
if (match(val)) {
result = val;
return false;
}

if (_.isObject(val) || _.isArray(val)) {
result = traverse(val);
}

if (result) {
return false;
}
});

return result;
}

return traverse(items);

}

[#77081] Tuesday, July 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaden

Total Points: 709
Total Questions: 91
Total Answers: 91

Location: Maldives
Member since Sat, Jan 29, 2022
2 Years ago
;