【问题标题】:Display data in tree structure in angular application在角度应用程序中以树结构显示数据
【发布时间】:2019-12-23 10:39:05
【问题描述】:

在我的应用程序中,我需要以树形结构的格式显示数据。

基本上,我需要根据列表中的 parent_id 缩进项目,因此它会创建一个树结构,请参见下面给出的屏幕截图,其中我根据它们在树结构中的位置进行缩进。

这是我收到的数据:

[
  {
    "id": 1,
    "title": "Item 1",
    "parent_id": null
  },
  {
    "id": 2,
    "title": "Item 2",
    "parent_id": 1
  },
  {
    "id": 3,
    "title": "Item 3",
    "parent_id": 2
  },
  {
    "id": 4,
    "title": "Item 4",
    "parent_id": null
  },
  {
    "id": 5,
    "title": "Item 5",
    "parent_id": null
  },
  {
    "id": 6,
    "title": "Item 6",
    "parent_id": 5
  },
  {
    "id": 7,
    "title": "Item 7",
    "parent_id": 6
  },
  {
    "id": 8,
    "title": "Item 8",
    "parent_id": 6
  }
]

我需要一些关于如何格式化这些数据的建议,以便它可以轻松地对其进行迭代并在前端显示它。目前正在考虑创建一个嵌套的对象数组,其中每个对象都将保存其子对象,如下所示。

[
  {
    "id": 1,
    "title": "Item 1",
    "parent_id": null,
    "child": [{
        "id": 2,
        "title": "Item 2",
        "parent_id": 1,
        "child": [{
            "id": 3,
            "title": "Item 3",
            "parent_id": 2
        }]
    }]
  },
  {
    "id": 4,
    "title": "Item 4",
    "parent_id": null
  },
  {
    "id": 5,
    "title": "Item 5",
    "parent_id": null,
    "child": [{
        "id": 6,
        "title": "Item 6",
        "parent_id": 5,
        "child": [{
            "id": 7,
            "title": "Item 7",
            "parent_id": 6
        }, {
            "id": 8,
            "title": "Item 8",
            "parent_id": 6
        }]
    }]
  }
]

【问题讨论】:

  • 正确,您可以创建所需格式的嵌套数组
  • 是的,对象数组对你来说就足够了,对于这个结构,请使用“Angular Hierarchical Tree View Component”
  • 您想要创建层次结构的解决方案吗?

标签: javascript arrays angular object


【解决方案1】:

你可以垫树。这非常简单和有用。您可以使用 css 根据您的意愿自定义设计。官方文档:https://material.angular.io/components/tree/overview

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多