Convert delimited string into hierarchical JSON wi

2020-01-30 06:57发布

问题:

I have an array of strings that describe the parent/child relationship by being delimited with dashes. So, if Bob's boss was Jim and Jim's boss was Fred, Bob's entry in the array would be "Fred-Jim-Bob" and Jim's entry would be "Fred-Jim." I don't have the ability to change the way the data is coming in so I was looking for help as far as the best way of turning these values into JSON similar to this:

{
    "name": "Fred",
    "children": {
        "name": "Jim",
        "children": {
            "name": "Bob"
        }
    }
}

Any help would be greatly appreciated. Thanks.

回答1:

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;
        }
    }
}

output JSONifies as:

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