相关疑难解决方法(0)

使用父字段从平面列表构造层次结构树?

我有一个带有parent字段的"页面"对象列表.此父字段引用列表中的另一个对象.我想基于此字段从此列表中创建树层次结构.

这是我的原始列表:

[
  {
    id: 1,
    title: 'home',
    parent: null
  },
  {
    id: 2,
    title: 'about',
    parent: null
  },
  {
    id: 3,
    title: 'team',
    parent: 2
  },
  {
    id: 4,
    title: 'company',
    parent: 2
  }
]
Run Code Online (Sandbox Code Playgroud)

我想将它转换为这样的树结构:

[
  {
    id: 1,
    title: 'home',
    parent: null
  },
  {
    id: 2,
    title: 'about',
    parent: null,
    children:  [
      {
        id: 3,
        title: 'team',
        parent: 2
      },
      {
        id: 4,
        title: 'company',
        parent: 2
      }
    ]
]
Run Code Online (Sandbox Code Playgroud)

我希望有一个可重用的函数,我可以随时调用任意列表.有人知道处理这个问题的好方法吗?任何帮助或建议将不胜感激!

javascript arrays tree json hierarchy

18
推荐指数
2
解决办法
2万
查看次数

标签 统计

arrays ×1

hierarchy ×1

javascript ×1

json ×1

tree ×1