我的问题与Convert delimited string into hierarchical JSON with JQuery
有关我有一个类似的任务,我必须从分隔的字符串创建一个json对象:
var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];
输出
[{
"name": "Fred",
"children": [{
"name": "Jim",
"children": [{
"name": "Bob",
"children": []
}]
}, {
"name": "Thomas",
"children": [{
"name": "Rob",
"children": []
}]
}]
}]
区别在于每个节点没有更多子节点 必须有一个名为“last”的附加子节点,如:
{
"name": "Thomas",
"children": [{
"name": "Rob",
"children": [],
"last":true
}
我是否可以检测节点是否没有更多子节点并使用此算法在那里添加其他节点?
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;
}
}
}
提前谢谢。
答案 0 :(得分:2)
如果您对输入列表进行了排序,则可以通过这种方式确定某些内容中没有更多子项: