vincej
2 months ago

How to best format data for use in jqTree

Posted 2 months ago by vincej

jqTree requires the data coming off your controller to be in a specific format:

var data = [
    {
        name: 'node1', id: 1,
        children: [
            { name: 'child1', id: 2 },
            { name: 'child2', id: 3 }
        ]
    },
    {
        name: 'node2', id: 4,
        children: [
            { name: 'child3', id: 5 }
        ]
    }
];


I found on SO some code which works BUT the code does not include the ID of the category. Ugh. I have tried frigging with the Javascript to include the category_id but all I get is errors. So - I have two options, either try to fix the SO code or develop my script to convert my collection to fit jqTree. If someone can point me towards how to fix the SO code, then that would be easiest. If I have to develop my own JS script to reformat my collection, then I have offered the format of my collection below.

Here is the SO code:

var jqTreeData = function (data) {
        var source = [];
        var items = [];
        // build hierarchical source.
        for (i = 0; i < data.length; i++) {
            var item = data[i];
            var title = item["Title"];
            var reportsToId = item["ReportsToId"];
            var id = item["Id"];

            if (items[reportsToId]) {
                var item =
                {
                    label: title
                };

                if (!items[reportsToId].children) {
                    items[reportsToId].children = [];
                }

                items[reportsToId].children[items[reportsToId].children.length] = item;
                items[id] = item;
            }
            else {
                items[id] =
                {
                    label: title
                };

                source[0] = items[id];
            }
        }
        return source;
    }


My data coming off of my controller is in a collection and looks like this:

 1 => App\Models\Category {#660 ▼
     
      #attributes: array:10 [▼
        "category_id" => 53
        "parent_id" => "1"
        "lft" => 10
        "rgt" => 21
        "depth" => 1
        "name" => "Materials"
        "notes" => null
        "status" => "active"
        "created_at" => "2020-04-01 11:48:28"
        "updated_at" => null
      ]

So, somehow, by magic, I have to get my data reformatted into the jqTree structure. Each node of the tree has a parent_id. Each category_id might / maybe also have children.

Many Thanks to all !!

Please sign in or create an account to participate in this conversation.