[英]Parent-Child TreeView in Javascript from JSON file
我想創建一個對象數組。 並且每個對象可能再次具有JSON文件中的對象數組。 JSOn中的每個對象都有一個parent_id,它告訴它屬於哪個ID。
"data":[
{
"id":"node_0",
"intentName":"pdf"
"parent_id":"-1"
},
{
"id":"node_2",
"intentName":"Key Leadership",
"parent_id":"node_0"
},
{
"id":"node_3",
"intentName":"Financial Results",
"parent_id":"node_0"
},
{
"id":"node_1",
"intentName":"Business Summary",
"parent_id":"node_0"
},
{
"id":"node_7",
"intentName":"Key Strategy",
"parent_id":"node_1"
},
{
"id":"node_34",
"intentName":"CompanyInReport",
"parent_id":"node_1"
},
{
"id":"node_36",
"intentName":"Operating Locations",
"parent_id":"node_0"
}]
這是JSON文件,具有parent_id(-1表示根父級,其他表示其父級ID)。 我想在啟動時動態創建一個如下所示的數組。
menuItems = [
{
title: 'Key Leadership'
},
{
title: 'Financial Results'
},
{
title: 'Business Summary',
values: [
{ title: 'Key Strategy'},
{ title: 'CompanyInReport'}
]
},
{
title: 'Operating Locations'
}]
提前致謝。
您不僅可以使用節點信息id
,還可以使用parent_id
來創建樹,然后將節點信息分配給該節點,並將父信息分配給父節點。
通過以任意順序獲取節點,可以形成樹形結構。
結果,僅采用所需父節點的值,在這種情況下為"node_0"
。
var data = [{ id: "node_0", intentName: "pdf", parent_id: "-1" }, { id: "node_2", intentName: "Key Leadership", parent_id: "node_0" }, { id: "node_3", intentName: "Financial Results", parent_id: "node_0" }, { id: "node_1", intentName: "Business Summary", parent_id: "node_0" }, { id: "node_7", intentName: "Key Strategy", parent_id: "node_1" }, { id: "node_34", intentName: "CompanyInReport", parent_id: "node_1" }, { id: "node_36", intentName: "Operating Locations", parent_id: "node_0" }], tree = function (data, root) { var o = {}; data.forEach(({ id, intentName: title, parent_id }) => { Object.assign(o[id] = o[id] || {}, { title }); o[parent_id] = o[parent_id] || {}; o[parent_id].values = o[parent_id].values || []; o[parent_id].values.push(o[id]); }); return o[root].values; }(data, 'node_0'); console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.