How to display a javascript object as an HTML tree?

by cortez.connelly , in category: Javascript , 7 months ago

How to display a javascript object as an HTML tree?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 7 months ago

@cortez.connelly 

There are multiple ways to display a JavaScript object as an HTML tree. Here's one approach using recursive function calls:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html>
<head>
  <style>
    ul {
      list-style-type: none;
      padding-left: 20px;
    }
  </style>
</head>
<body>
  <div id="tree"></div>

  <script>
    function displayObjectTree(obj, parentElement) {
      var ul = document.createElement('ul');
      
      for (var key in obj) {
        var li = document.createElement('li');
        li.innerText = key;
        
        if (typeof obj[key] === 'object') {
          displayObjectTree(obj[key], li);
        }
        
        ul.appendChild(li);
      }
      
      // Append the ul element to the parent element
      parentElement.appendChild(ul);
    }

    // Example object
    var myObject = {
      name: 'John',
      age: 30,
      address: {
        street: '123 Main St',
        city: 'New York',
        state: 'NY'
      }
    };

    // Display the object tree
    displayObjectTree(myObject, document.getElementById('tree'));
  </script>
</body>
</html>


In this example, we create a recursive function displayObjectTree that takes the object and the parent HTML element as parameters. It creates a <ul> element and iterates through the properties of the object. For each property, it creates a <li> element and sets its text to the key. If the property value is also an object, it recursively calls displayObjectTree to create a nested sub-tree. Finally, it appends the <li> element to the <ul> element.


Note: You can customize the styling of the tree by modifying the CSS code provided.