需要将数组转换为:
[
{value: 'a', depth: 1, children: []},
{value: 'c', depth: 2, children: []},
{value: 'd', depth: 2, children: []},
{value: 'e', depth: 1, children: []},
{value: 'f', depth: 2, children: []},
{value: 'g', depth: 3, children: []},
{value: 'i', depth: 4, children: []},
// depth can bee any int but the integer row is respected
{value: 'j', depth: n, children: []},
// ...
{value: 'z', depth: 3, children: []},
]
进入:
[
{value: 'a', depth: 1, children: [
{value: 'c', depth: 2, children: null},
{value: 'd', depth: 2, children: null},
]},
{value: 'e', depth: 1, children: [
{value: 'f', depth: 2, children: [
{value: 'g', depth: 3, children: [
{value: 'i', depth: 4, children: [
{value: 'j', depth: n, children: [
// ...
]},
]},
]},
{value: '', depth: 3, children: null},
]},
]},
]
非常感谢!
我知道我应该使用递归函数,但是会卡在这里。
答案 0 :(得分:1)
不需要递归。您可以对级别使用辅助数组,并将depth
设为从零开始的值(此值需要调整)。
对父子关系的选择是基于顺序的,因此子项会跟随前一个depth元素的最后一个父项。
var array = [{ value: 'a', depth: 1, children: [] }, { value: 'c', depth: 2, children: [] }, { value: 'd', depth: 2, children: [] }, { value: 'e', depth: 1, children: [] }, { value: 'f', depth: 2, children: [] }, { value: 'g', depth: 3, children: [] }, { value: 'i', depth: 4, children: [] }, { value: 'z', depth: 3, children: [] }],
result = [],
levels = [{ children: result }];
array.forEach(o => levels[o.depth - 1].children.push(levels[o.depth] = o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }