我有一个字符串数组,用破折号分隔来描述父/子关系。因此,如果鲍勃的老板是吉姆,而吉姆的老板是弗雷德,则鲍勃在数组中的条目将是“弗雷德-吉姆- 鲍勃”,而吉姆的条目将是“弗雷德-吉姆”。我没有能力更改数据输入的方式,因此我一直在寻求帮助,以将这些值转换为类似于以下内容的JSON的最佳方法:
{ "name": "Fred", "children": { "name": "Jim", "children": { "name": "Bob" } } }
任何帮助将不胜感激。谢谢。
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": [] }] }] }]