I am new to Javascript, I had some classes, but I still found out about it, and I was working on creating a tree from JSON. I looked at other answers here, but I just can't figure out what this reduction, recursion, and jquery thingys are. So I made my own functions.
But first, my JSON looks like this:
var data = [{ "id": 51, "name": "root" }, { "id": 54, "name": "app", "parentId": 53 }, { "id": 55, "name": "text.txt", "parentId": 54 }, { "id": 53, "name": "share", "parentId": 52 }, { "id": 52, "name": "local", "parentId": 51 }];
And these functions process the JSON object:
var treeNode = function(nodeId, name) { var children = []; this.nodeId = nodeId; this.name = name; this.parentNode = null; this.setParent = function(parentNode) { this.parentNode = parentNode; }; this.addChild = function(node){ children.push(node); node.setParent(this); }; }; var Tree = function() { this.nodes = []; this.findNodeById = function(nodeId) { for (var i=0; i<this.nodes.length; i++) { if (this.nodes[i].nodeId === nodeId) { return this.nodes[i]; } } return null; }; this.createNode = function(nodeId, name, parentNode) { var node = new treeNode(nodeId, name); if (parentNode) { parentNode.addChild(node); } this.nodes.push(node); } }; function createTree(data) { var tree = new Tree(); var temp = []; for (var i=0; i<data.length; i++) { var inputNode = data[i]; var parentNode = inputNode.parentId ? tree.findNodeById(inputNode.parentId) : null; tree.createNode(inputNode.id, inputNode.name, parentNode); } return tree.nodes; }
Then I call the function: createTree (data);
So, after a lot of debugging trying to make functions, etc., I finally realized that I can make a mistake somewhere, because now the parents for the nodes for 54 and 53 are not displayed, and I just canβt wrap my head that I I'm doing it wrong and how can I fix it? Can someone help me?
Any suggestions are greatly appreciated.