【发布时间】:2015-04-23 15:21:07
【问题描述】:
我有一个来自 JSON 的 JS 数据结构,如下所示:
[
{
"eid": "T1",
"name": "Topic1",
"children": [
{
"eId": "T1.1",
"name": "subtopic1",
"children": []
},
{
"eId": "T1.2",
"name": "subtopic2"
}
]
},
{
"eId": "T2",
"name": "Topic1",
"children": []
}
]
我需要迭代它并构造另一个结构,如下所示:
[
{
"id": "T1",
"text": "Topic1",
"children": [
{
"id": "T1.1",
"text": "subtopic1",
"children": []
},
{
"id": "T1.2",
"text": "subtopic2"
}
]
},
{
"id": "T2",
"text": "Topic1",
"children": []
}
]
我的代码在这里
// topics = the first strucutre
var treeData=[];
for(var i=0,len=topics.length;i<len;++i)
{
var topicElements=topics[i];
var subNodes=[];
var nodes={};
nodes['id']=topicElements.eId;
nodes['text']=topicElements.name;
for (var j =0;j<topicElements.children.length;++j)
{
nodesChildren = topicElements.children;
position = subNodes.length;
subNodes[position] = new Object();
subNodes[position]['id']=nodesChildren[j].eId;
subNodes[position]['text']=nodesChildren[j].name;
}
nodes['children']=subNodes;
treeData.push(nodes);
}
它适用于一个级别,但如果我必须遍历 T1.1 的子级,那么它将不起作用。你能建议我一种递归的方式吗?
【问题讨论】:
标签: javascript recursion