Skip to content

Instantly share code, notes, and snippets.

@onel0p3z
Created April 9, 2013 22:04
Show Gist options
  • Save onel0p3z/5349828 to your computer and use it in GitHub Desktop.
Save onel0p3z/5349828 to your computer and use it in GitHub Desktop.
From SO#15909638, I whipped this for loop to create a tree-like structure to create a menu using http://jsfiddle.net/zzal/qdvuN/10/ as example
var PlaceHolder = "PlaceHolder";
var myArr =
[{id:5, parentid:0, text:PlaceHolder},
{id:6, parentid:0, text:PlaceHolder},
{id:7, parentid:0, text:PlaceHolder},
{id:8, parentid:7, text:PlaceHolder},
{id:9, parentid:7, text:PlaceHolder},
{id:10, parentid:5, text:PlaceHolder},
{id:11, parentid:5, text:PlaceHolder},
{id:12, parentid:7, text:PlaceHolder},
{id:15, parentid:0, text:PlaceHolder},
{id:16, parentid:15, text:PlaceHolder},
{id:17, parentid:5, text:PlaceHolder},
{id:18, parentid:15, text:PlaceHolder},
{id:19, parentid:15, text:PlaceHolder},
{id:20, parentid:0, text:PlaceHolder},
{id:21, parentid:15, text:PlaceHolder},
{id:23, parentid:5, text:PlaceHolder}];
for (var i = 0; i < myArr.length; i++){
//console.log("outer: "+myArr[i].id)
myArr[i].children = [];
for (var q = 0; q < myArr.length; q++){
//console.log("inner: "+myArr[q].id)
if (myArr[i].id == myArr[q].parentid){
// if want to keep the parentid key
//var temp = {id:myArr[q].id,parentid:myArr[q],text:myArr[q].text}
var temp = {id:myArr[q].id,text:myArr[q].text};
myArr[i].children.push(temp);
};
};
};
// Create menu from tree-like structure array
// http://jsfiddle.net/zzal/qdvuN/10/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment