来自JSON文件的Javascript中的父子TreeView

问题描述 投票:1回答:1

我想创建一个对象数组。并且每个对象可以再次具有来自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"
        }]

这是具有parent_id的JSON文件(-1表示根父,其他表示其父ID)。我想在启动时动态创建一个类似下面的数组。

menuItems = [
  {
    title: 'Key Leadership'
  },
  {
    title: 'Financial Results'
  },
  {
    title: 'Business Summary',
    values: [
      { title: 'Key Strategy'},
      { title: 'CompanyInReport'}
    ]
  },
  {
    title: 'Operating Locations'
  }]

提前致谢。

javascript arrays treeview
1个回答
0
投票

您不仅可以使用节点信息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; }
© www.soinside.com 2019 - 2024. All rights reserved.