I have to arrange list of given array in form of a parent child array. I am able to do that with nested if-else statement but am unable to do that with function recursion. Below is the code for working nested if-else method and not-working function recursion method.
Here are the arrays
var arr = [
{"parent": "root", "name": "one"},
{"parent": "one", "name": "one one" },
{"parent": "one one", "name": "one one one"},
{"parent": "one one", "name": "one one two"},
{"parent": "root", "name": "two"},
{"parent": "root", "name": "three"},
{"parent": "root", "name": "four"},
{"parent": "four", "name": "four one"},
{"parent": "four one", "name": "four one one"},
{"parent": "four one", "name": "four one two"}];
var output111 = { 'parent': "0", 'name': "root", 'folder_list' : [] };
var output222 = { 'parent': "0", 'name': "root", 'folder_list' : [] };
Here is the nested if-else method which works perfectly
function getTreeHardCoded (parent) {
for ( i = 0; i < arr.length; i++) {
if( arr[i].parent === parent.name ) {
var folderListI = {parent : arr[i].parent, name : arr[i].name, folder_list : []};
parent.folder_list.push(folderListI);
for ( j = 0; j < arr.length; j++) {
if( arr[j].parent === arr[i].name ) {
var folderListJ = { parent: arr[j].parent, name: arr[j].name, folder_list:[]};
folderListI.folder_list.push(folderListJ);
for ( k = 0; k < arr.length; k++) {
if( arr[k].parent === arr[j].name ) {
var folderListK = { parent : arr[k].parent, name : arr[k].name, folder_list : [] };
folderListJ.folder_list.push(folderListK);
}
}
}
}
}
}
}
getTreeHardCoded(output111);
Here is function recursion method which do not work
function getTree (parent) {
for ( i = 0; i < arr.length; i++) {
if( arr[i].parent === parent.name ) {
var folderList = {
parent : arr[i].parent,
name : arr[i].name,
folder_list : []
};
parent.folder_list.push(folderList);
getTree(folderList);
}
}
}
getTree(output222);
Here is the FIDDLE with complete code, having desired output in white bg and output with function recursion in gray bg .
Thanks in advance..
Talk about globals biting you in the ass! Put a var
in front of all of your index variables ( i
, j
, and k
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.