troubleshooting Question

iterating through a nested JSON object

Avatar of Techsavy
Techsavy asked on
2 Comments2 Solutions2114 ViewsLast Modified:

I build a nested JSON object for a list of strings delimited by '-' to build a heirarchy. I was successfully able to get the nested JSON object from the Script below. However now I want to list this heirarchy in JSON object in HTML using div tags so I can indent children is this possible at all.?

var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];
var output = [];
for (var i = 0; i < input.length; i++) {
    var chain = inputi.split("-");
    var currentNode = output;
    for (var j = 0; j < chain.length; j++) {
        var wantedNode = chainj;
        var lastNode = currentNode;
        for (var k = 0; k < currentNode.length; k++) {
            if ( == wantedNode) {
                currentNode = currentNode[k].children;
        // If we couldn't find an item in this list of children
        // that has the right name, create one:
        if (lastNode == currentNode) {
            var newNode = currentNode[k] = {name: wantedNode, children: []};
            currentNode = newNode.children;

output JSONifies as:

    "name": "Fred",
    "children": [{
        "name": "Jim",
        "children": [{
            "name": "Bob",
            "children": []
    }, {
        "name": "Thomas",
        "children": [{
            "name": "Rob",
            "children": []
Pierre Cornelius

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros