使用JQuery将分隔的字符串转换为分层JSON

时间:2011-06-03 21:13:04

标签: jquery json hierarchy organization

我有一个字符串数组,通过用短划线分隔来描述父/子关系。因此,如果鲍勃的老板是吉姆,而吉姆的老板是弗雷德,那么鲍勃在阵中的入口将是“弗雷德 - 吉姆 - 鲍勃”,吉姆的入口将是“弗雷德 - 吉姆”。 我没有能力改变数据进入的方式所以我一直在寻找帮助,就像将这些值转换为JSON的最佳方式类似:

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

非常感谢任何帮助。 感谢。

1 个答案:

答案 0 :(得分:31)

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

输出JSONifies为:

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