Link to home
Create AccountLog in
Avatar of Techsavy
Techsavy

asked on

iterating through a nested JSON object

Hi,

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 (currentNodek.name == wantedNode) {
                currentNode = currentNode[k].children;
                break;
            }
        }
        // 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": []
        }]
    }]
}]
SOLUTION
Avatar of clockwatcher
clockwatcher

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
ASKER CERTIFIED SOLUTION
Avatar of Pierre Cornelius
Pierre Cornelius
Flag of South Africa image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.