From the server, I receive this JSON object. It represents an organigram of a company and the associated departments.
I need to be able to choose a company, and with the ID of the company, I need to pass to an array of numbers the ID's of the associated departments.
For that, I've created this recursive function. It works, but, skips 3 departments, which are placed within another department
This is the JSON file
{
"cd": 1,
"cd_base": 0,
"nome": "EMPRESA A",
"children": [
{
"cd": 2,
"cd_base": 1,
"nome": "Departamento A",
"children": [
{
"cd": 4,
"cd_base": 2,
"nome": "Serviço A1",
"children": []
},
{
"cd": 15,
"cd_base": 2,
"nome": "Serviço A2",
"children": []
}
]
},
{
"cd": 3,
"cd_base": 1,
"nome": "Departamento B",
"children": [
{
"cd": 7,
"cd_base": 3,
"nome": "Serviço B1",
"children": []
}
]
},
{
"cd": 186,
"cd_base": 1,
"nome": "Departamento XX",
"children": []
}
]
}
And this is the function in Typescript
recursiveFunction(res: any): any[] {
const numbers = new Array(); // to store the ID
console.log('Im on ' + res.cd + ' | ' + res.nome);
numbers.push(res.cd);
if (res.children.length > 0) {
console.log(res.cd + ' | ' + res.nome + ' has children');
res.children.forEach((row) => {
numbers.push(row.cd);
this.recursiveFunction(row);
});
} else {
console.log(res.cd + ' | ' + res.nome + ' doesn\'t have any children');
}
return numbers;
}
And this is the return of that function to the console
Im on 1 | EMPRESA A
1 | EMPRESA A has c
Im on 2 | Departamento A
2 | Departamento A has children
Im on 4 | Serviço A1
4 | Serviço A1 doesn't have any children
Im on 15 | Serviço A2
15 | Serviço A2 doesn't have any children
Im on 3 | Departamento B
3 | Departamento B has children
Im on 7 | Serviço B1
7 | Serviço B1 doesn't have any children
Im on 186 | Departamento XX
186 | Departamento XX doesn't have any children
Then I log the numbers array and the result is 1,2,3,186
this.numbers.forEach(row => {
console.log(row);
});
// 1, 2, 3, 186
It adds the CD 1, 2, 3 and 186, but skips the 4, 7 and 15. All of those are a branch/node within another branch/node
What am I missing? Is recursive the best way to do this? Is there a simpler way?
Any help is appreciated
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)