I have a flatter array like this
const arr =
[ { org_level_code: 'BBI', org_level_name: 'Bostwick', org_level_parent_code: 'toplevel', children: null }
, { org_level_code: 'CDI', org_level_name: 'BBi US', org_level_parent_code: 'BBI', children: null }
, { org_level_code: '60', org_level_name: '60 - Sidney1', org_level_parent_code: 'BBI/CDI', children: null }
, { org_level_code: 'BBC', org_level_name: 'BBi Canada', org_level_parent_code: 'BBI/CDI', children: null }
, { org_level_code: 'BBI-2', org_level_name: 'BBi U.S. ', org_level_parent_code: 'BBI/CDI', children: null }
, { org_level_code: 'DEPT', org_level_name: 'Dept', org_level_parent_code: 'BBI/CDI/BBI-2', children: null }
]
From this array I need the array like this
const data =
[ { org_level_code: 'BBI', org_level_name: 'Bostwick', org_level_parent_code: 'toplevel', children:
[ { org_level_code: 'CDI', org_level_name: 'BBi US', org_level_parent_code: 'BBI', children:
[ { org_level_code: 'BBC', org_level_name: 'BBi Canada', org_level_parent_code: 'BBI/CDI', children: null }
, { org_level_code: '60', org_level_name: '60 - Sidney1', org_level_parent_code: 'BBI/CDI', children: null }
, { org_level_code: 'BBI-2', org_level_name: 'BBi U.S. ', org_level_parent_code: 'BBI/CDI', children:
[ { org_level_code: 'DEPT', org_level_name: 'Dept', org_level_parent_code: 'BBI/CDI/BBI-2', children: null }
] } ] } ] } ]
As you can see in the example "org_level_parent_code": "toplevel"
is the parent node and "org_level_parent_code": "BBI"
is the second node of parent because first node has the relation with child one with "org_level_code": "BBI"
and "org_level_parent_code": "BBI/CDI"
indicates the 3rd level. These slash separated string has the relation with their respective parent nodes.
The last string e.g. BBI-2
of the slash separated string has the relation with above node.
Note- Top level node can be multiple like "org_level_parent_code": "toplevel"
.
I am really struggling hard to achieve this. Please help.