The following is the original array that I want to convert, its structure is the same as columns of andt
const base = [
{
name: "Jonh"
},
{
name: "jane"
},
{
name: "Tom",
children: [
{
name: "Jery"
},
{
name: "Mart"
},
{
name: "Mary",
children: [
{
name: "bob"
}
]
}
]
},
{
name: "boboy"
}
]
And this is the array I want to convert into
My simple wish is to bring children out to the same level as its parent array and still keep its parent intact
const result = [
{
name: "Jonh"
},
{
name: "jane"
},
{
name: "Tom",
children: [
{
name: "Jery"
},
{
name: "Mart"
},
{
name: "Mary",
children: [
{
name: "bob"
}
]
}
]
},
[
{
name: "Jery"
},
{
name: "Mart"
},
{
name: "Mary",
children: [
{
name: "bob"
}
]
},
[
{
name: "bob"
}
],
],
{
name: "boboy"
}
]
For some people it’s easy but I’m new and hope everyone can help
Here’s what I tried
const filterChild = (listColumn: IColumns[]): any[] => {
return listColumn.map((col) => {
return col.children ? filterChild(col.children) : col;
});
};
The purpose of this action is that I am trying to create a custom table with the "Grouping table head" function like andt’s.
3
Answers
Thank you guys for answering my question and I have based on your answers and found my solution as follows:
};
This is a problem that can be easily handled by recursion. Here is one such example of using recursion (and a helper function) to achieve this very task.
Note that I’m using an arrow syntax function here… But you could have just as easily defined the function like
function bringOutChildren(arr){
… to do the exact same thing. You can read about recursion here . If you would like to read up about the javascript array concatenation you can read up about that hereEDIT
Because @Robby Cornelisson’s comments, I have decided to show a function that will give the exact output the SO author originally had (in case it wasn’t a mistake)… In which case we change one line of code in the "bringOutChildren" function.
You can use this function in the same way the original was.
Here is a recursive solution. The idea is to recursively process the children, and add the processed child array to the output.
Note: review the output of the snippet in the browser’s console. The snippet editor’s output will replace the duplicated nodes with references.