[英]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.