简体   繁体   中英

Hierarchical Depth Level logic in JSON data using Javascript

Just want to know your code logic using javascript in this problem. I want to put a depth level tracking in my hierarchical data. The data can have more layers.

This is my sample data

Raw data

I want to put a depth attribute in each

Edited Data

Sample Data

[{
"id": 1,
"label": "System",
"parent_id": null,
"description": "System Manager",
"children": [{
    "id": 2,
    "label": "base",
    "parent_id": 1,
    "description": "Base Manager",
    "children": [{
        "id": 3,
        "label": "Menus",
        "parent_id": 2,
        "description": "menu manager",

    },
    {
        "id": 4,
        "label": "Roles",
        "parent_id": 2,
        "description": "Role Manager",

    },
    {
        "id": 5,
        "label": "Users",
        "parent_id": 2,
        "description": "User Manager",

    }]
}]
},
{
    "id": 6,
    "label": "Customs",
    "parent_id": null,
    "description": "Custom Manager",
    "children": [{
        "id": 7,
        "label": "CustomList",
        "parent_id": 6,
        "description": "CustomList",

    }]
}

But there you go. I've boiled down your data to a simple example. As you can see Iam using a recursive function which will be incremented with each call to the next level.

 var example = [{ "id": 1, "label": "System", "parent_id": null, "description": "System Manager", "children": [{ "id": 2, "label": "base", "parent_id": 1, "description": "Base Manager", "children": [{ "id": 3, "label": "Menus", "parent_id": 2, "description": "menu manager" }, { "id": 4, "label": "Roles", "parent_id": 2, "description": "Role Manager", }, { "id": 5, "label": "Users", "parent_id": 2, "description": "User Manager" }] }] }, { "id": 6, "label": "Customs", "parent_id": null, "description": "Custom Manager", "children": [{ "id": 7, "label": "CustomList", "parent_id": 6, "description": "CustomList" }] }]; var res = document.getElementById("res"); var addDepth = function(json, depth){ return json.map(e => { e.depth = depth; if(e.children){ e.children = addDepth(e.children, depth + 1); } return e; }); } res.innerHTML = JSON.stringify(addDepth(example, 0), undefined, 2); 
 <pre id="res"></pre> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM