Multi-level collection filter
https://codereview.stackexchange.com/questions/148273/filtering-a-deep-array
by Sam_Butler
HTML
<input id="filter" type="text" value="nursery">
<button type="button" id="search">Go</button>
<pre id="results">
</pre>
JavaScript
$('#search').click(function(){
$('#results').html('');
var val = $('#filter').val();
var output = filterData(anzsic, function(item) {
return item.description.toUpperCase().includes(val.toUpperCase()) || item.code.includes(val);
});
console.log(output);
$('#results').text(JSON.stringify(output,null,1));
});
function filterData(data, predicate) {
// if no data is sent in, return null, otherwise transform the data
return !!!data ? null : data.reduce((list, entry) => {
let clone = null;
if (predicate(entry)) {
// if the object matches the filter, clone it as it is
clone = Object.assign({}, entry);
} else if (entry.children != null) {
// if the object has childrens, filter the list of children
let children = filterData(entry.children, predicate);
if (children.length > 0) {
// if any of the children matches, clone the parent object, overwrite
// the children list with the filtered list
clone = Object.assign({}, entry, {children: children});
}
}
// if there's a cloned object, push it to the output list
clone && list.push(clone);
return list;
}, []);
}
/*function filter(array, key, search) {
var result = [];
array.forEach(function (a) {
var temp = [],
o = {},
found = false;
if (a[key] === search) {
o[key] = a[key];
found = true;
}
if (Array.isArray(a.children)) {
temp = filter(a.children, search);
if (temp.length) {
o.children = temp;
found = true;
}
}
if (found) {
result.push(o);
}
});
return result;
}*/
//console.log(filter(array, 'something'));
var anzsic = [{"type":"division","code":"A","description":"Agriculture, Forestry and Fishing","children":[{"type":"anzsic","parent":"A","parent_type":"division","code":"0111","description":"Nursery Production (Under...