检查json树是否没有更多的子树

时间:2023-02-03 12:26:01

my question relates to Convert delimited string into hierarchical JSON with JQuery

我的问题是用JQuery将分隔字符串转换成分层JSON。

I have a similar task where I have to create a json object from a delimited string as:

我有一个类似的任务,我必须从一个分隔的字符串创建一个json对象:

var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];

which outputs

的输出

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

With the difference that each node that does not have more children has to have an additional sub-node called "last", like that:

由于每个节点没有更多的子节点,所以必须有一个额外的子节点,称为“last”,比如:

{
    "name": "Thomas",
    "children": [{
        "name": "Rob",
        "children": [],
        "last":true

}

Can I detect if a node has no more children and add an additional node there using this algorithm?

我是否可以检测一个节点是否没有子节点,并使用此算法添加一个额外的节点?

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

Thank you in advance.

提前谢谢你。

1 个解决方案

#1


2  

If you sorted the input list, you could identify that something doesn't have any more children this way:

如果你对输入列表进行排序,你可以通过这种方式识别出某物不再有子元素:

  1. let's say you're at "NodeA-NodeB-NodeC".
  2. 假设你在“noda - nodeb-nodec”。
  3. if you move right in the list, you'd have to move to something later in the alphabet, so if there was no "NodeA-NodeB" as part of the list item you move to, then NodeB doesn't have any more children.
  4. 如果你在列表中右移,你将不得不在字母表中移动到后面的东西,所以如果没有“NodeA-NodeB”作为列表项的一部分,那么NodeB就没有更多的孩子了。

#1


2  

If you sorted the input list, you could identify that something doesn't have any more children this way:

如果你对输入列表进行排序,你可以通过这种方式识别出某物不再有子元素:

  1. let's say you're at "NodeA-NodeB-NodeC".
  2. 假设你在“noda - nodeb-nodec”。
  3. if you move right in the list, you'd have to move to something later in the alphabet, so if there was no "NodeA-NodeB" as part of the list item you move to, then NodeB doesn't have any more children.
  4. 如果你在列表中右移,你将不得不在字母表中移动到后面的东西,所以如果没有“NodeA-NodeB”作为列表项的一部分,那么NodeB就没有更多的孩子了。