I am working with a potentially infinite tree-view array:
type Tree = {
id: number;
name: string;
email: string;
children: Tree[];
};
const tree: Tree[] = [
{
id: 1,
name: 'Truck',
email: '@mail',
children: [
{
id: 11,
name: 'Car',
email: '@mail',
children: [],
},
],
},
{
id: 2,
name: 'Bus',
email: '@mail',
children: [],
},
];
There are 3 modifications I need to make to this array:
- change the property key 'id' to 'userId'
- change the id type from number to string
- remove the email property
so the new output will adhere to this type:
type NewTree = {
userId: string;
name: string;
children: NewTree[];
};
// output of the new tree
const newTree: NewTree[] = [
{
userId: '1',
name: 'Truck',
children: [
{
userId: '11',
name: 'Car',
children: [],
},
],
},
{
userId: '2',
name: 'Bus'
children: [],
},
];
This is my current implementation
const restructuredTree = (tree: any[]) => {
for (const node in tree) {
const { id: userId, name, children } = tree[node];
restructuredTree(children);
tree[node] = { userId, name, children };
}
};
I'm unsure where to place a return statement, and when I return "tree[node] = { userId, name, children };", it only affects one level deep.