javascriptjsonrecursionjavascript-objectsnested-json

How to recursively build a JSON tree structure in JavaScript?


I wrote an recursive function to generate an hierarchy JSON but the function is returning unexpected output i tried solving it but i am getting no where.

The input format is a list of objects with Name,Email,Reports to Id(parent node) and Id and i converted the above list of objects into a map where key is Reports to Id and value is array objects who are directly reporting to the parent node

My Recursive Function:


function buildTree(mainRoot) {
  const items = [
    {
      label: mainRoot.Name,
      name: mainRoot.Name,
      expanded: true,
      items: [],
    },
  ];
  if (directReportee.has(mainRoot.Id)) {
    directReportee.get(mainRoot.Id).forEach((childNodes) => {
        items[0].items.push(buildTree(childNodes));
    });
  }
 
  return items;
}

Output Format my function returning:

[
  {
    "label": "Lauren Boyle",
    "name": "Lauren Boyle",
    "expanded": true,
    "items": [
      [
        {
          "label": "Banoth Srikanth",
          "name": "Banoth Srikanth",
          "expanded": true,
          "items": [
            [
              {
                "label": "Stella Pavlova",
                "name": "Stella Pavlova",
                "expanded": true,
                "items": []
              }
            ]
          ]
        }
      ],
      [
        {
          "label": "Srikanth",
          "name": "Srikanth",
          "expanded": true,
          "items": []
        }
      ]
    ]
  }
]

My output needs to items keys as list of object instead of list inside list of objects

Expected Output Format:

items = [
        {
            label: 'Western Sales Director',
            name: '1',
            expanded: true,
            items: [
                {
                    label: 'Western Sales Manager',
                    name: '2',
                    expanded: true,
                    items: [
                        {
                            label: 'CA Sales Rep',
                            name: '3',
                            expanded: true,
                            items: [],
                        },
                        {
                            label: 'OR Sales Rep',
                            name: '4',
                            expanded: true,
                            items: [],
                        },
                    ],
                },
            ],
        }
    ]
    


Solution

  • items[0].items.push(buildTree(childNodes));
    

    try instead

    items.items.push(buildTree(childNodes));
    

    It might be helpful if you renamed that const 'items' variable to 'item'. I'd also suggest naming that lambda parameter 'childNodes' to 'childNode'.