我有一个数组,其中包含具有父子关系的嵌套对象,如下所示:
[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4, children: []},
{id: 6, title: 'hello', parent: 4, children: []}
]},
{id: 7, title: 'hello', parent: 3, children: []}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2, children: []}
]}
]
我需要将它转换为一个普通数组,并保留类似于父子关系的结构,按照父级和其所有子元素先返回,然后再继续下一个父级。
[
{id: 1, title: 'hello', parent: 0},
{id: 3, title: 'hello', parent: 1},
{id: 4, title: 'hello', parent: 3},
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4},
{id: 7, title: 'hello', parent: 3},
{id: 2, title: 'hello', parent: 0},
{id: 8, title: 'hello', parent: 2}
]
我可以使用递归函数将其转换回来。
但是我需要以高效的方式执行相反的操作。如示例嵌套数组所示,存在多级嵌套。
编辑:更新嵌套数组以便叶节点具有空的子数组。
此外,ES5中的答案将会有所帮助。
breadth-first-search
,但是你的扁平数组是深度优先搜索的输出。 - trincot