3

Recently I've encounter a problem, I need to create a html nested list from irregular JavaScript object, and I'm not sure how to proceed with this task. Basically I have JavaScript object which represents 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 what I need to do with this is to create ul with nested li's for each folder (the path should be ommited here).

I would greatly appreciate any help with this one.

Thank you.

2
  • 1
    With a data structure of unknown depth, you usually want to go for a recursive function ... Commented Jun 29, 2017 at 9:07
  • possible duplicate stackoverflow.com/questions/19357176/… Commented Jun 29, 2017 at 9:13

1 Answer 1

0

Depth first traversal of the object can be 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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.