我的问题与使用 JQuery 将分隔字符串转换为分层 JSON 有关
我有一个类似的任务,我必须从分隔字符串创建一个 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;
}
}
}
先感谢您。