Skip to content

Instantly share code, notes, and snippets.

@kiennt2
Last active November 10, 2018 21:07
Show Gist options
  • Save kiennt2/ced642964881126281b9ba2e71895957 to your computer and use it in GitHub Desktop.
Save kiennt2/ced642964881126281b9ba2e71895957 to your computer and use it in GitHub Desktop.
Filter - Tree - JSON
var data = [
{
name: 'a1', children: [
{
name: 'b1', children: [
{ name: 'gap' }, { name: 'bar' }
]
}
]
},
{
name: 'a2', children: [
{
name: 'b2', children: [
{ name: 'foo' }, { name: 'gap' }
]
}
]
},
{
name: 'a3', children: [
{
name: 'b3', children: [
{ name: 'foo' }, { name: 'gap' }
]
}
]
}
];
function filterData(data, predicate) {
// if no data is sent in, return null, otherwise transform the data
return !!!data ? null : data.reduce(function (list, entry) {
var clone = null;
if (predicate(entry)) {
// if the object matches the filter, clone it as it is
clone = (JSON.parse(JSON.stringify(entry)));
} else if (entry.children != null) {
// if the object has childrens, filter the list of children
var 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 = (JSON.parse(JSON.stringify(entry)));
clone.children = children;
}
}
// if there's a cloned object, push it to the output list
clone && list.push(clone);
return list;
}, []);
}
function highlightKeyword(key, data) {
var reg = new RegExp(key, "gi");
return data.replace(reg, function (str) {
return '<b class="highlight">' + str + '</b>'
});
}
function buildList(data, isSub) {
var html = (isSub) ? '<div class="sub-content">' : '';
html += '<ul>';
for (var item in data) {
console.log(data);
html += '<li>';
if (typeof(data[item].children) === 'object') {
html += '<div class="item-title">';
html += '<a href="javascript:void(0);" data-id="' + data[item].id + '" title="' + data[item].name + '">' + data[item].name + '</a>';
html += '<span class="arrow"><i class="fa fa-angle-right"></i></span>';
html += '</div>';
html += buildList(data[item].children, true);
} else {
html += '<div class="item-title">';
html += '<a href="javascript:void(0);" data-id="' + data[item].id + '" title="' + data[item].name + '">' + data[item].name + '</a>';
html += '</div>';
}
html += '</li>';
}
html += '</ul>';
html += (isSub) ? '</div>' : '';
return html;
}
function valueExist(key, str) {
key = key.toLowerCase();
str = str.toLowerCase();
return str.indexOf(key) > -1;
}
var result = filterData(data, function (item) {
if (valueExist('fo', item.name) {
return item.name;
}
});
console.log(JSON.stringify(result, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment