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);
}
You could take an iterative and recursive approach.
function find(id, array) {
var result;
array.some(o => o.id === id && (result = o) || (result = find(id, o.children || [])));
return result;
}
var objects = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar', children: [{ id: 3, name: 'baz', children: [{ id: 4, name: 'foobar' }] }] }];
console.log(find(1, objects));
console.log(find(2, objects));
console.log(find(3, objects));
console.log(find(4, objects));
.as-console-wrapper { max-height: 100% !important; top: 0; }