使用JQuery将定界字符串转换为分层JSON

使用JQuery将定界字符串转换为分层JSON,第1张

使用JQuery将定界字符串转换为分层JSON
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;        }    }}

输出JSONify为:

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存