1

I am trying to write a function that takes a flat data format which uses a id and a parentId to establish relationships. I know I need to use recursion but I need help understanding how to get it in a specific JSON model.

Here is the flat source data, the id's are guids as you can see.

 {"id":"e6168d55-1974-e411-80e0-005056971214","parentId":"","label":"OGC File List"}
 {"id":"17168d55-1974-e411-80e0-005056971214","parentId":"e6168d55-1974-e411-80e0-005056971214","label":"Accounting"}
 {"id":"h37s8d55-1974-e411-80e0-005056971214","parentId":"17168d55-1974-e411-80e0-005056971214","label":"Policy"}
 {"id":"f8ke6d55-1974-e411-80e0-005056971214","parentId":"17168d55-1974-e411-80e0-005056971214","label":"Policy"}

Below is the model I need to create. I only need help with the properties id: inode: which indicates the node has children and the branch which is the array of child objects. Building the branches is what confounds me the most. I appreciate any assistance or direction in advance!

[
 {
 id: 'folder_1',
 label: 'This is Folder 1',
 inode: true,
 open: false,
 icon: 'folder'
 branch:
 [
 {
 id: 'sub-item_x',
 label: 'This is File X',
 inode: false,
 icon: 'file'
 },
 ...
 ]
 },
 {
 id: 'file_1',
 label: 'This is File 1',
 inode: false,
 icon: 'file'
 },
 ...
 ]
asked Dec 4, 2014 at 16:26

1 Answer 1

2

Try with this code:

var list = [{...},{...},...{...}]; //folder list in JSON format == JS object
var tree = buildChildrenList(''); //find root folders first
function buildChildrenList(parentId){
 var childrens = [];
 for(var i=0;i<list.length;i++){
 if (list[i].parentId == parentId){
 childrens.push({
 id: list[i].id,
 label: list[i].label,
 inode: true,
 open: false,
 icon: 'folder',
 branch: buildChildrenList(list[i].id) //this is a recursive call
 });
 }
 }
 return childrens;
}
answered Dec 4, 2014 at 16:55
Sign up to request clarification or add additional context in comments.

2 Comments

I'm attempting to test now. branch: is getting a error "missing }". I'm trying to figure it out.
Thank you Ragnar, I wish I could up-vote this 10 times, very clean and way more simple than my approach.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.