Hello I have json file:
var jsonData = {
"name": "James",
"age": 22,
"nodes": [
{
"name": "John",
"age": 24,
"nodes": [
{
"name": "Jack",
"age": 65,
"nodes": [
{
"name": "Harry",
"age": 70,
"nodes": []
}
]
},
{
"name": "Joe",
"age": 10,
"nodes": []
}
]
},
{
"name": "Daniel",
"age": 30,
"nodes": []
}
]
}
I need a function that returns output like this:
James 22
James - John 24
James - John - Jack 65
James - John - Jack - Harry 70
James - John - Joe 10
James - Daniel 30
I tried to use recursive function but I don't know how to return output like this one and return age only on last child..
Code:
var json = jsonData;
var prev = [];
function sortData(obj, prev) {
var i = 0;
prev.push(obj.name + " " + obj.age);
console.log(prev);
if (obj.nodes.length > 0) {
while (i < obj.nodes.length) {
sortData(obj.nodes[i], prev);
i++;
prev.pop();
}
}
}
sortData(json, prev);
My function returns output in multiple arrays, so I don't know how to operate with that to return output like that. Will be grateful for any help. Thanks!