Skip to content
This repository has been archived by the owner on Mar 7, 2024. It is now read-only.

[Feature Helper ] JS Array Helper #193

Open
harun opened this issue Sep 2, 2020 · 0 comments
Open

[Feature Helper ] JS Array Helper #193

harun opened this issue Sep 2, 2020 · 0 comments

Comments

@harun
Copy link

harun commented Sep 2, 2020

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.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant