Question

my question relates to Convert delimited string into hierarchical JSON with JQuery

I have a similar task where I have to create a json object from a delimited string as:

var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];

which outputs

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

With the difference that each node that does not have more children has to have an additional sub-node called "last", like that:

{
    "name": "Thomas",
    "children": [{
        "name": "Rob",
        "children": [],
        "last":true

}

Can I detect if a node has no more children and add an additional node there using this algorithm?

var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];
var output = [];
for (var i = 0; i < input.length; i++) {
var chain = input[i].split("-");
var currentNode = output;
for (var j = 0; j < chain.length; j++) {
    var wantedNode = chain[j];
    var lastNode = currentNode;
    for (var k = 0; k < currentNode.length; k++) {
        if (currentNode[k].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;
    }
}
}

Thank you in advance.

Was it helpful?

Solution

If you sorted the input list, you could identify that something doesn't have any more children this way:

  1. let's say you're at "NodeA-NodeB-NodeC".
  2. if you move right in the list, you'd have to move to something later in the alphabet, so if there was no "NodeA-NodeB" as part of the list item you move to, then NodeB doesn't have any more children.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top