I am new to Javascript and programming in general. I am working with a list of "step" objects that have a choice/solution field which references another object in the same list. My goal is to create a tree hierarchy based on this field.
[ Below is the array file that I want to restructure into a tree :
$scope.nodes = {
"story": {
"step" : [
{
"title": "Begin",
"id": "0",
"type": "MultipleChoice",
"description": "Starting point of the adventure.",
"choice": [
{
"nextStepId": "1",
"#text": "Born as a troll, tough luck."
}]
},
{
"title": "Choice",
"id": "1",
"type": "MultipleChoice",
"description": "Time to take control of your life.",
"choice": [
{
"nextStepId": "1001",
"#text": "Take an apple"
},
{
"nextStepId": "4",
"#text": "Suicide"
},
{
"nextStepId": "1001",
"#text": "Use a coin to decide"
}
]
},
{
"title": "Riddle",
"id": "4",
"type": "Riddle",
"description": "Best way to end it all?",
"solution": {
"nextStep": "1000",
"#text": "think"
}
},
{
"title": "you are dead",
"id": "1000",
"type": "End",
"win": "true",
"description": "Rest in peace."
},
{
"title": "you are alive",
"id": "1001",
"type": "End",
"win": "false",
"description": "You survived."
}
]
}
}
My progress so far :
$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)
(Note: A child can have multiple parents, and 'choice' may contain an array or single element.)
It seems like there's an issue with the 'choice' being undefined.
I would appreciate any guidance on correcting my code. I prefer to learn from my mistakes but open to suggestions.
Thank you!