只想在这个问题中使用javascript了解你的代码逻辑。 我想在我的分层数据中加入深度级别跟踪。数据可以有更多层。
这是我的样本数据
我想在每个
中加上深度属性样本数据
[{
"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",
}]
}
答案 0 :(得分:0)
但是你去了。我把你的数据归结为一个简单的例子。正如您所见,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>