I have an array with objects of unknown depth, like this
var objects = [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar',
childs: [{
id: 3,
name: 'baz',
childs: [{
id: 4,
name: 'foobar'
}]
}]
}];
I would like to be able to filter a specific child object by it's id.
Currently I am using this little lodash script (referred from this question) but it works only with objects not deeper than one level. So searching for id: 1
and id: 2
would work fine while searching for id: 3
or id: 4
would return undefined.
function deepFilter(obj, search) {
return _(obj)
.thru(function(coll) {
return _.union(coll, _.map(coll, 'children'));
})
.flatten()
.find(search);
}