我是一名Javascript新手,也是编程初学者。我有一个带有选择/解决方案字段的“步骤”对象列表。此选择/解决方案字段引用列表中的另一个对象。我想根据这个字段从这个列表创建一个树形层次结构。在孩子有多个父母的树状结构中显示扁平列表?
[这里是数组文件我想重组就像一棵树:
$scope.nodes = {
"story": {
"step" : [
{
"title": "Begin",
"id": "0",
"type": "MultipleChoice",
"description": "Yo, bro it's the start of the adventure !",
"choice": [
{
"nextStepId": "1",
"#text": "You was born as a troll, no luck in life. :'("
}]
},
{
"title": "Choice",
"id": "1",
"type": "MultipleChoice",
"description": "It's time to take your life back, and choice what you should do !",
"choice": [
{
"nextStepId": "1001",
"#text": "Take an apple"
},
{
"nextStepId": "4",
"#text": "Suicide"
},
{
"nextStepId": "1001",
"#text": "You use a coin to know what to do"
}
]
},
{
"title": "Riddle",
"id": "4",
"type": "Riddle",
"description": "What is the best way to suicide ?",
"solution": {
"nextStep": "1000",
"#text": "think"
}
},
{
"title": "you are dead",
"id": "1000",
"type": "End",
"win": "true",
"description": "Nice, you are dead finally !"
},
{
"title": "you are alive",
"id": "1001",
"type": "End",
"win": "false",
"description": "Damn, you are still alive !"
}
]
}
}
,这里是我做过什么至今:
$scope.tree = function tree() {
var map = {}, node, roots = [];
for (var i = 0; i < nodes.length; i += 1) {
node = nodes.story.step[i];
map[node.id] = i;
if (node.id !== "0") {
switch (node.type) {
case ("MultipleChoice"):
for (var j = 0; i < node.choice.length; j += 1)
nodes[map[node.id]].choice[j].nextStepId[j].push(node);
break;
case ("Riddle"):
nodes[map[node.id]].solution.nextStep[j].push(node);
break;
case ("End"):
//TO DO
}
}
else {
roots.push(node);
}
}
}(nodes)
(请注意,儿童(选择/解决方案)可以有多个父代,并且'choice'可以是一个数组或一个元素。)
显然,我做错了什么。选择是'undefined'
请问你能改正我?我不知道。我希望保留自己的代码以从错误中学习,但如果您有其他建议,请随时提供。
非常感谢你
这个问题是不是除了这两个有区别吗? http://stackoverflow.com/questions/37743204/constructing-a-tree-from-a-json-array-in-javascript http://stackoverflow.com/questions/37716801/constructing-a-hierarchical-tree-from -a-json-array – hatchet
是的,它是。约束是不同的 – Takichiii
停止重复相同的问题!更新一个不会创建一个新的一遍又一遍。您几分钟前再次询问同一个问题,并在澄清问题后将其删除。这不是如何使用这个网站 – charlietfl