I have a nested and hierarchical array of objects, which looks like this
JavaScript
x
26
26
1
[{
2
"id": 0,
3
"name": "E00-E90 Stoffwechselstörungen",
4
"parentId": null,
5
"children": [{
6
"id": 1,
7
"name": "E70-E90 Stoffwechselstörungen",
8
"parentId": 0,
9
"children": [{
10
"id": 2,
11
"name": "E70.- Störungen des Stoffwechsels aromatischer Aminosäuren",
12
"parentId": 1,
13
"children": []
14
}, {
15
"id": 3,
16
"name": "E71.- Störungen des Stoffwechsels verzweigter Aminosäuren und des Fettsäurestoffwechsels",
17
"parentId": 1,
18
"children": []
19
}, {
20
"id": 4,
21
"name": "E72.- Sonstige Störungen des Aminosäurestoffwechsels",
22
"parentId": 1,
23
"children": []
24
},
25
26
Now I want to remove the empty array "children": []
from the last children.
I’ve tried it with reduce
but it doesn’t work without any error.
JavaScript
1
14
14
1
var lastElementLength = list.length - 1
2
3
const findItemNested = (arr, itemId, nestingKey) => (
4
arr.reduce((a, item) => {
5
if (a) return a;
6
if (item.id === itemId) return item;
7
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
8
}, null)
9
);
10
11
const resEmptyChildren = findItemNested(roots, lastElementLength, "children");
12
13
console.log('resEmptyChildren', resEmptyChildren)
14
Advertisement
Answer
You could use recursion for that.
JavaScript
1
43
43
1
var tInput = [{
2
"id": 0,
3
"name": "E00-E90 Stoffwechselstörungen",
4
"parentId": null,
5
"children": [{
6
"id": 1,
7
"name": "E70-E90 Stoffwechselstörungen",
8
"parentId": 0,
9
"children": [{
10
"id": 2,
11
"name": "E70.- Störungen des Stoffwechsels aromatischer Aminosäuren",
12
"parentId": 1,
13
"children": []
14
}, {
15
"id": 3,
16
"name": "E71.- Störungen des Stoffwechsels verzweigter Aminosäuren und des Fettsäurestoffwechsels",
17
"parentId": 1,
18
"children": []
19
}, {
20
"id": 4,
21
"name": "E72.- Sonstige Störungen des Aminosäurestoffwechsels",
22
"parentId": 1,
23
"children": []
24
}]
25
}]
26
}];
27
28
(function removeEmptyChildrenProperties(input){
29
console.log('Checking id:', input.id);
30
if(input.hasOwnProperty('children')){
31
if(input.children && input.children.length){
32
input.children.forEach(removeEmptyChildrenProperties)
33
}
34
else{
35
console.log('Remove children on id:', input.id);
36
delete input.children
37
}
38
};
39
40
return input
41
}).apply(null, tInput);
42
43
console.log(JSON.stringify(tInput));