javascriptjqueryjsontree

Printing a JSON object in hierarchical/tree format


Object:

[
   {
      "Item":{
         "Name":"User 4"
      },
      "Children":[
         
      ]
   },
   {
      "Item":{
         "Name":"User 1"
      },
      "Children":[
         {
            "Item":{
               "Name":"User 6"
            }
         },
         {
            "Item":{
               "Name":"User 2"
            }
         }
      ]
   }
]

I am traversing this object with the following code:

(function Traverse(o) {
    for (var i in o) {
        console.log('Value: ' + o[i].Item.Name);

        if (o[i].Children !== null && o[i].Children !== [] && typeof(o[i].Children) == "object") {
            Traverse(o[i].Children);
        }
    }
  })
(data);

Output:

value: User 4
value: User 1
value: User 6
value: User 2
undefined

I want the output to be in a hierarchal/tree format. I have found several libraries but I do not want a proper graphical representation, just a simple use of text to indicate the hierarchy.

Something like this:

enter image description here

P.S. I am not a javascript programmer.


Solution

  • You could use this recursive function. As an example I have used an object with a bit more items and levels:

    function toText(arr) {
        const recur = ({Item, Children}) => Item?.Name + 
            (Children?.length ? "\n" + Children.map(recur).map((text, i, {length}) =>
                i < length-1 ? "├──" + text.replace(/\n/g, "\n│  ")
                             : "└──" + text.replace(/\n/g, "\n   ")
            ).join("\n") : "")
        return arr.map(recur).join("\n");
    }
    
    // Example:
    let arr = [{
        "Item": {
            "Name": "A"
        },
        "Children": [
        ]
    }, {
        "Item": {
            "Name": "B"
        },
        "Children": [{
            "Item": {
               "Name": "BA"
            },
            "Children": [{
                "Item": {
                    "Name": "BAA"
                },
                "Children": [{
                    "Item": {
                        "Name": "BAAA"
                    }
                }, {
                    "Item": {
                        "Name": "BAAB"
                    }
                }, {
                    "Item": {
                        "Name": "BAAC"
                    }
                }]
            }, {
                "Item": {
                    "Name": "BAB"
                },
                "Children": [{
                    "Item": {
                        "Name": "BABA"
                    }
                }]
           }]
        }, {
            "Item":{
                "Name": "BB"
            }
        }]
    }];
    console.log(toText(arr));