The guys are trying to create a dynamic menu list. There is no limit to the depth of elements that can be created by the user.
MY PROBLEM
My set of URLs is as follows:
var json_data = [ { "title" : "Food", "path" : "/root", }, { "title" : "Cloths", "path" : "/root", }, { "title" : "Veg", "path" : "/root/Food", }, { "title" : "Brinjal", "path" : "/root/Food/Veg", }, { "title" : "T shirt", "path" : "/root/Cloths", }, { "title" : "Shirt", "path" : "/root/Cloths", }, { "title" : "Green brinjal", "path" : "/root/Food/Veg/Brinjal", } ];
I want titles be in a hierarchy format, which I will eventually create in the form ul > li to create a menu in the interface.
The hierarchy should be something like this:
[ { "title": "Food", "path": "/root", "children": [ { "title": "Veg", "path": "/root/Food", "children": [ { "title": "Brinjal", "path": "/root/Food/Veg", "children": [ { "title": "Green brinjal", "path": "/root/Food/Veg/Brinjal", "children": [] } ] } ] } ] }, { "title": "Cloths", "path": "/root", "children": [ { "title": "T shirt", "path": "/root/Cloths", "children": [] }, { "title": "Shirt", "path": "/root/Cloths", "children": [] } ] } ]
WHAT DID I SAY
// Add an item node in the tree, at the right position function addToTree( node, treeNodes ) { // Check if the item node should inserted in a subnode for ( var i=0; i<treeNodes.length; i++ ) { var treeNode = treeNodes[i]; // "/store/travel".indexOf( '/store/' ) if ( node.path.indexOf( treeNode.path + '/' ) == 0 ) { addToTree( node, treeNode.children ); // Item node was added, we can quit return; } } // Item node was not added to a subnode, so it a sibling of these treeNodes treeNodes.push({ title: node.title, path: node.path, children: [] }); } //Create the item tree starting from menuItems function createTree( nodes ){ var tree = []; for ( var i=0; i<nodes.length; i++ ) { var node = nodes[i]; addToTree( node, tree ); } return tree; } // variable = "json_data" is the set of URLS var menuItemsTree = createTree( json_data ); console.log(menuItemsTree)
And the result he gives is this:
[ { "title": "Food", "path": "/root", "children": [ { "title": "Veg", "path": "/root/Food", "children": [ { "title": "Brinjal", "path": "/root/Food/Veg", "children": [ { "title": "Green brinjal", "path": "/root/Food/Veg/Brinjal", "children": [] } ] } ] }, { "title": "T shirt", "path": "/root/Cloths", "children": [] }, { "title": "Shirt", "path": "/root/Cloths", "children": [] } ] }, { "title": "Cloths", "path": "/root", "children": [] } ]
The elements "T Shirt" and "Shirt" are placed inside the children in food: [] , which should be inside the fabric of children: []
The solution I used is taken from here
I try to output the algorithm myself, but it has not yet been clicked for sure. Please help if someone already has a solution. In case I can get a solution on my own, I will share it here. higher code thanks