【发布时间】:2015-07-29 16:46:35
【问题描述】:
在以下结构中有一个对象数组
[
{id: 1, title: 'hello', parent: 0},
{id: 2, 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: 8, title: 'hello', parent: 2}
]
我想创建一个具有以下结构的新数组
[
{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},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
]
【问题讨论】:
-
既然您基本上是在谈论如何构建和利用树结构,那么让我指出一个可能相关的问题。 stackoverflow.com/questions/8640823/… 没有像原始问题一样标记为重复并不清楚所需的数据格式是否是硬性要求。