Skip to content

Instantly share code, notes, and snippets.

@sshadmand
Last active Oct 15, 2016
Embed
What would you like to do?
Recursive Filter on Tree Dict (JSON)
outline = [{
id: 1,
children: [{
id: 3,
label: 'goodbye',
children: []
}],
label: 'hello'
},
{
id: 2,
children: [{
id: 9,
label: 'mama',
children: []
}],
label: 'dada'
}];
function searchTree(treeArr, searchId){
var arr = []
for (nodeIndex in treeArr) {
var node = treeArr[nodeIndex];
if (node.id == searchId) {
console.log("Macth. Ignoring", node.id);
} else {
if (node.children.length > 0) {
var newChildren = searchTree(node.children, searchId, node);
node.children = newChildren;
arr.push(node);
} else {
arr.push(node);
return arr;
}
}
}
return arr;
}
a = searchTree(outline, 9)
console.log(a)
// Lazy. Scan entire tree and filter any nodes that match
function deleteNodeFromTree(obj, removeNodeId) {
obj.children = obj.children.filter(item => item.id != removeNodeId);
for (nodeIndex in obj.children) {
deleteNodeFromTree(obj.children[nodeIndex], removeNodeId, parentNodeId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment