Follow up question to Flat array to tree Javascript
Looking for a solution of how to flatten a tree structure into an an array that can be used to insert into a sql db.
Some other solutions I've found use recursion, but I was hoping to find an explanation of how a recursive solution would work.
const tree = [
{
1: {
label: 'root',
children: [
{
2: {
label: 'ant',
children: [],
},
},
{
3: {
label: 'bear',
children: [
{
4: {
label: 'cat',
children: [],
},
},
{
5: {
label: 'dog',
children: [
{
6: {
label: 'elephant',
children: [],
},
},
],
},
},
],
},
},
{
7: {
label: 'frog',
children: [],
},
},
],
},
},
];
const expectedFlattenedTree = [
{ id: 1, label: 'root', parent_id: null },
{ id: 2, label: 'ant', parent_id: 1 },
{ id: 3, label: 'bear', parent_id: 1 },
{ id: 4, label: 'cat', parent_id: 3 },
{ id: 5, label: 'dog', parent_id: 3 },
{ id: 6, label: 'elephant', parent_id: 5 },
{ id: 7, label: 'frog', parent_id: 1 },
];