I have an object structured as follows:
interface Employee {
id: number;
name: string;
parentid: number;
level: string;
children?: Employee[];
}
const Data: Employee[] = [
{
id:1, name: 'name1', parentid:0, level: 'L1',
children: [
{ id: 2, name: 'name2', parentid:1, level: 'L2'},
{ id: 3, name: 'name3', parentid:1, level: 'L2',
children: [
{id: 4, name: 'name4', parentid:3, level: 'L3'}
]}
]
}
];
In this structure, the children's parentid corresponds to the parent data's 'id'.
If new data with [id=5, name:'name5', parentid=0 and Level='L1'] is provided along with its child data [id=6, name='name6'], we need to check if the given id=5 exists in L1. If not, it should be added like so:
[
{
id:1, name: 'name1', parentid:0, level: 'L1',
children: [
{ id: 2, name: 'name2', parentid:1, level: 'L2'},
{ id: 3, name: 'name3', parentid:1, level: 'L2',
children: [
{id: 4, name: 'name4', parentid:3, level: 'L3'}
]}
]
},
{
id:5, name: 'name5', parentid:0, level: 'L1',
children: [
{ id: 6, name: 'name6', parentid:5, level: 'L2'}
]
}
];
If a new entry with id:7, name:'name7', and parentid=3 is encountered, then it should be placed under the data with id 3 as shown below:
[
{
id:1, name: 'name1', parentid:0, level: 'L1',
children: [
{ id: 2, name: 'name2', parentid:1, level: 'L2'},
{ id: 3, name: 'name3', parentid:1, level: 'L2',
children: [
{id: 4, name: 'name4', parentid:3, level: 'L3'},
{id: 7, name: 'name7', parentid:3, level: 'L3'}
]}
]
},
{
id:5, name: 'name5', parentid:0, level: 'L1',
children: [
{ id: 6, name: 'name6', parentid:5, level: 'L2'}
]
}
];
Please provide guidance on this matter.