[英]Hierarchical Depth Level logic in JSON data using Javascript
Just want to know your code logic using javascript in this problem. 只想知道您在此问题中使用javascript的代码逻辑。 I want to put a depth level tracking in my hierarchical data.
我想在层次数据中进行深度级别跟踪。 The data can have more layers.
数据可以具有更多层。
This is my sample data 这是我的样本数据
I want to put a depth attribute in each 我想在每个属性中放置一个depth属性
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.
如您所见,Iam使用的是递归函数,每次调用都会将其递增到下一个级别。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.