0%

tree remove item

https://stackoverflow.com/questions/17964757/how-to-prune-delete-nodes-in-nested-tree-like-json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var a =  [
{
"label": "node1",
"children": [
{
"label": "Human"
},
{
"label": "Chimpanzee"
}
]
},
{
"label": "node2",
"children": [
{
"label": "node3",
"children": [
{
"label": "Rat"
},
{
"label": "Mouse"
}
]
},
{
"label": "BigRat"
}
]
}
]

function prune(array, label) {
for (var i = 0; i < array.length; ++i) {
var obj = array[i];
if (obj.label === label) {
// splice out 1 element starting at position i
array.splice(i, 1);
return true;
}
if (obj.children) {
if (prune(obj.children, label)) {
if (obj.children.length === 0) {
// delete children property when empty
delete obj.children;

// or, to delete this parent altogether
// as a result of it having no more children
// do this instead
array.splice(i, 1);
}
return true;
}
}
}
}

var wasItPruned = prune(tree, "node3");