Create nested HTML list from irregular javascript object (folder structure)

I recently ran into a problem, I need to create an html nested list from an irregular JavaScript object, and I'm not sure how to proceed with this task. Basically I have a JavaScript object that represents the folder structure as a tree:

var obj = {
  "Canmon01-srv-13": {
    "tidata": {
      "Comite Paritaire SST": {
        "Securite Machine" : {
          "01- Development" : {
            "path": "Canmon01-srv-13/tidata/Comite Paritaire SST/4_Securite_Machine/01 - Developpement"
          }
        }
      }
    }
  },

  "Cantor-srv-36" : {
    "TM1-USAEWD01" : {
      "path": "CANTOR01-SRV-36/TM1-USAEWD01"
    }
  },

  "FP&A" : {
    "path" : "FP&A" 
  }
}

      

Basically I need to do this to create a ul with a nested li for each folder (the path must be omitted here ).

I would really appreciate any help with this.

Thank.

+3


source to share


1 answer


The depth of the first traversal of the object can help:



<html>
<body>
    <div id="dir"></div>
</body>
<script>
    var obj = {
        "Canmon01-srv-13": {
            "tidata": {
                "Comite Paritaire SST": {
                    "Securite Machine" : {
                        "01- Development" : {
                            "path": "Canmon01-srv-13/tidata/Comite Paritaire SST/4_Securite_Machine/01 - Developpement"
                        }
                    }
                }
            }
        },

        "Cantor-srv-36" : {
            "TM1-USAEWD01" : {
                "path": "CANTOR01-SRV-36/TM1-USAEWD01"
            }
        },

        "FP&A" : {
            "path" : "FP&A"
        }
    };

    var traverse = function(node, str) {
        var keys = Object.keys(node);
        if(keys.length === 1 && keys[0] === 'path') {
            str += "</li>";
            return str;
        }
        str += "<ul>";
        keys.forEach(k => {
            str += "<li>" + k;
            str = traverse(node[k], str);
        });
        str += "</ul>";
        return str;
    };
    document.getElementById('dir').innerHTML = traverse(obj, "");
</script>
</html>
      

Run codeHide result


0


source







All Articles