Mohsin Arif
Mohsin Arif

Reputation: 18

Making a Tree like Structure in Json With Recursion

I'm struggling to get my head around this one, i've had a few attempts and failed miserably.

Basically I have a list of Employees in a database, each with an ID. A Employee can have a parent Employee (Refer as Manager).

I need to output the structure in some sort of tree in json format like shown in this URL

https://raw.githubusercontent.com/bumbeishvili/Assets/master/Projects/D3/Organization%20Chart/redesignedChartLongData.json

Here is a very basic structure example enter image description here

Upvotes: 0

Views: 72

Answers (1)

Attersson
Attersson

Reputation: 4866

The JSON can have a structure like this, containing an array of employees:

{
    "employees":[
        {
            "id": 1764,
            "name": "Maaz",
            ... //other fields... this employee has no parent field or
            // "parent" : 0 (invalid value)
        },
        {
            "id": 1765,
            "parent": 1764,
             //other fields... this employee has Maaz as parent
        }
    ]
}

"parent" can simply be an optional field of the employee, containing theid of the parent employee.

If the json had a recursion (i.e. "parent": { /*...*/ }) this would create several issues such as:

  • Will the parent employee only be stored as second level, or also appear in the list as top level? This adds redundancy or alternatively, search complexity. because if 1764 only appears as child of 1765, you have to potentially recursively trasverse the whole list tree in order to find any employee.
  • What is the maximum depth of the recursion? With trasversal problems.
  • Inconsistency or circular relations, leading to loops. If A is parent of B and B is parent of A. Or if there is redundancy but upon deletion the employee does not get wiped anywhere.
  • More complex operations: if you have a chain of 5 parent-child employees and remove the top one, what do you do with the rest? You would have to define a policy. And adjust the tree everytime.

A flat list on the other hand required just 2 O(n) searches when you are looking for example, for employee 1765. You will then find its parent id and search the list again for an employee with than id, if it exists.

When you add an employee, add without a parent field and edit it later. When you delete an employee, just delete it and eventual broken links will be found at (flat) search time.

Upvotes: 1

Related Questions