GoBeavs
GoBeavs

Reputation: 499

Recursion using JSON

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'
        },
        ...
    ]

Upvotes: 1

Views: 74

Answers (1)

Ragnar
Ragnar

Reputation: 4578

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;
}

Upvotes: 2

Related Questions