adgsm / multi-level-push-menu

MultiLevelPushMenu jQuery Plugin implementation
http://multi-level-push-menu.dzunic.net
804 stars 213 forks source link

[Feature Helper ] JS Array Helper #193

Open harun opened 4 years ago

harun commented 4 years ago

I am trying to convert parent-child related flat data to tree list data.

Flat json data:


    {
        "name": "Devices",
        "id": 1,
        "parentId": null
    },
    {
        "name": "Mobile Phones",
        "id": 2,
        "parentId": 1
    },
    {
        "name": "Super Smart Phone",
        "id": 3,
        "parentId": 1
    },
    {
        "name": "Thin Magic Mobile",
        "id": 4,
        "parentId": 1
    },
    {
        "name": "Cameras",
        "id": 5,
        "parentId": null
    },
    {
        "name": "Smart Shot",
        "id": 6,
        "parentId": 5
    },
    {
        "name": "Power Shooter",
        "id": 7,
        "parentId": 5
    },
    {
        "name": "Easy Photo Maker",
        "id": 8,
        "parentId": 5
    }

]

`function treeify(list, idAttr, parentAttr, childrenAttr) {
    if (!idAttr) idAttr = 'id';
    if (!parentAttr) parentAttr = 'parent';
    if (!childrenAttr) childrenAttr = 'children';

    var treeList = [];
    var lookup = {};
    list.forEach(function(obj) {
        lookup[obj[idAttr]] = obj;
        obj[childrenAttr] = [];
    });
    list.forEach(function(obj) {
        if (obj[parentAttr] != null) {
            lookup[obj[parentAttr]][childrenAttr].push(obj);
        } else {
            treeList.push(obj);
        }
    });
    return treeList;
};
`

`var treeList = treeify(data, "id", "parentId", "items")`

But I could not managed !
Is it possible to make helper for js array ?
Thank you.