我是一名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