根据字段值从对象的平面数组制作层次树

时间:2019-04-01 08:53:15

标签: javascript data-structures

需要将数组转换为:

[
  {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},
    ]},
  ]},
]

非常感谢

我知道我应该使用递归函数,但是会卡在这里。

1 个答案:

答案 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; }