JSON 文件中 Javascript 中的父子树视图

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; }