I'm implementing a search for a deep array. It applies the search/filter to the deepest level of children below, i.e. { name: 'foo' }, { name: 'bar' }
.
If all children are filtered from the parent object, the parent is removed from the list too.
Since I want to leave the original object intact, I copy each container object and add a new children property to it.
I think this has a lot of room for improvement. It feels like it can be simplified. Also, this doesn't feel DRY.
var data = [
{
name: 'a1', children: [
{
name: 'b1', children: [
{ name: 'foo' }, { name: 'bar' }
]
}
]
},
{
name: 'a2', children: [
{
name: 'b2', children: [
{ name: 'baz' }, { name: 'bah' }
]
}
]
}
];
function filterData(data, filter){
var result = [];
_.forEach(data, function(firstLevelItem){
var newFirstLevelItem = _.extend({}, firstLevelItem, { children: [] });
_.forEach(firstLevelItem.children, function(secondLevelItem){
var newSecondLevelItem = _.extend({}, secondLevelItem, {
children: _.filter(secondLevelItem.children, filter)
});
if(newSecondLevelItem.children.length > 0) {
newFirstLevelItem.children.push(newSecondLevelItem);
}
});
if(newFirstLevelItem.children.length > 0) {
result.push(newFirstLevelItem);
}
});
return result;
}
var result = filterData(data, function(item){
return item.name === 'foo';
});
console.log(result);