I have this JSON payload, where each object contains an ID, name and array of children. Here I need to get the IDs of all the elements, including the root and all the nested children.
{
"_id": "-1",
"_name": "root",
"_children": [
{
"_id": "1",
"_name": "Child 1",
"_children": [
{
"_id": "1-1",
"_name": "Child 1-1",
"_children": [
{
"_id": "1-1-1",
"_name": "Child 1-1-1",
"_children": [
]
}
]
},
{
"_id": "1-2",
"_name": "Child 1-2",
"_children": [
]
},
{
"_id": "1-3",
"_name": "Child 1-3",
"_children": [
]
}
]
},
{
"_id": "2",
"_name": "Child 2",
"_children": [
{
"_id": "2-2",
"_name": "Child 2-2",
"_children": [
]
}
]
}
]
}
How can I loop through this to get the ID values of all children and the root?
This is what I had tried using a nested function, but it is not working.
getNestedChildren(arr) {
var out = []
for(var i in arr[0].children) {
out.push(arr[i].id);
if(arr[i].children && arr[i].children.size() > 0) {
var children = this.getNestedChildren(arr[i].children)
}
}