function jsFilter(idList){
var rsltHierarchy=[];
for (var i=0;i<hierarchy.length;i++) {
var currCatg=hierarchy[i];
var filtCatg={"title":currCatg.title, "children":[]};
for (var j=0;j<currCatg.children.length;j++) {
var currSub=currCatg.children[j];
var filtSub={"title":currSub.title, "children":[]}
for(var k=0; k<currSub.children.length;k++){
if(idList.indexOf(currSub.children[k].id)!==-1)
filtSub.children.push({"id":currSub.children[k].id, "title":currSub.children[k].title});
}
if(filtSub.children.length>0)
filtCatg.children.push(filtSub);
}
if(filtCatg.children.length>0)
rsltHierarchy.push(filtCatg);
}
return rsltHierarchy;
}
function jqFilter(idList){
var rsltHierarchy=[];
$.each(hierarchy, function(index,currCatg){
var filtCatg=$.extend(true, {}, currCatg);
filtCatg.children=[];
$.each(currCatg.children, function(index,currSub){
var filtSub=$.extend(true, {}, currSub);
filtSub.children=[];
$.each(currSub.children, function(index,currSubChild){
if(idList.indexOf(currSubChild.id)!==-1)
filtSub.children.push($.extend(true, {}, currSubChild));
});
if(filtSub.children.length>0)
filtCatg.children.push(filtSub);
});
if(filtCatg.children.length>0)
rsltHierarchy.push(filtCatg);
});
return rsltHierarchy;
}
var hierarchy = eval("("+document.getElementById("inp").value+")");
var IDs = eval("("+document.getElementById("txtBoxIds").value+")");
document.getElementById("oupJS").value=JSON.stringify(jsFilter(IDs));
$(function() {
$("#oupJQ").text(JSON.stringify(jqFilter(IDs)));
});
#inp,#oupJS,#oupJQ {width:400px;height:100px;display:block;clear:all}
#inp{height:200px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
ID List: <Input id="txtBoxIds" type="text" value="[2, 3]">
<p>Input:
<textarea id="inp">[
{
"title": "category 1",
"children": [
{"title": "subcategory 11",
"children": [
{"id": 1, "title": "name 1"},
{"id": 2, "title": "name 2"},
{"id": 3, "title": "name 3"}
]
},
{"title": "subcategory 12",
"children": [
{"id": 1, "title": "name 4"}
]
}
]
},
{
"title": "category 2",
"children": [
{"title": "subcategory 21",
"children": [
{"id": 3, "title": "name cat2sub1id3"},
{"id": 5, "title": "name cat2sub1id5"}
]
},
{"title": "subcategory 22",
"children": [
{"id": 6, "title": "name cat2sub2id6"},
{"id": 7, "title": "name cat2sub2id7"}
]
}
]
}
]</textarea>
<p>Pure-Javascript solution results:
<textarea id="oupJS"></textarea>
<p>jQuery solution results:
<textarea id="oupJQ"></textarea>