I have an array of object:
arrayOfObjects = [
{
"name": "A",
"child": [
{
"name": "A1",
"child": [
{
"name": "A1a"
},
{
"name": "A1b"
},
{
"name": "A1c"
}
]
},
{
"name": "A2",
"child": [
{
"name": "A2a"
},
{
"name": "A2b"
}
]
},
{
"name": "A3",
"child": [
{
"name": "A3a"
},
{
"name": "A3b"
},
{
"name": "A3c"
},
{
"name": "A3d"
}
]
},
{
"name": "A4",
"child": [
{
"name": "A4a"
},
{
"name": "A4b"
},
{
"name": "A4c"
}
]
}
]
},
{
"name": "B",
"child": [
{
"name": "B1",
"child": [
{
"name": "B1a"
},
{
"name": "B1b"
}
]
},
{
"name": "B2",
"child": [
{
"name": "B2a"
},
{
"name": "B2b"
}
]
},
{
"name": "B3",
"child": [
{
"name": "B3A"
},
{
"name": "B3b"
},
{
"name": "B3c"
},
{
"name": "B3d"
},
{
"name": "B3e"
}
]
}
]
},
{others objects with same structure}
]
I need to create an array of arrays from this array of object with this structure :
array = [[A,A1,A1a],
[A1b],
[A1c],
[A2,A2a],
[A2b],
[A3,A3a],
[A3b],
[A3c],
[A3d],
[A4,A4a],
[A4b],
[A4c],
[B,B1,B1a]
and so on]
The purpose is to writ a line for each array in a Google spreadsheet.
I’m getting lost with the forEach method, in each object, the child key contains other arrays of object having child themselves, I don’t know how to iterate in this hierarchy
2
Answers
I’ve done that…
synthetic result
You can achieve this using self-contained recursion (not relying on a global accumulator or passed context) by distributing the results of the deepest recursive calls across each level on the way back up. Here using a nested
for...of
loop on the results of the recursive call.But it is clearer both in logic and output to simply create complete rows for each child.