# 数据转换

// 问题
var arr1 = [
  {
    code: '1',
    children: [
      {
        code: '11',
        children: [
          {
            code: '111',
            children: [],
          },
          {
            code: '112',
            children: [],
          },
        ],
      },
    ],
  },
  {
    code: '2',
    children: [
      {
        code: '22',
        children: [
          {
            code: '221',
            children: [],
          },
          {
            code: '222',
            children: [],
          },
          {
            code: '223',
            children: [],
          },
        ],
      },
    ],
  },
  {
    code: '3',
    children: [
      {
        code: '33',
        children: [
          {
            code: '333',
            children: [],
          },
        ],
      },
    ],
  },
]
// arr1里面每一项下的层级都一样,如示例都是三级
// 转换后期望输出arr2:

var aar2 = [
  { code1: '1', code2: '11', code3: '111' },
  { code1: '1', code2: '11', code3: '112' },
  { code1: '2', code2: '22', code3: '221' },
  { code1: '2', code2: '22', code3: '222' },
  { code1: '2', code2: '22', code3: '223' },
  { code1: '3', code2: '33', code3: '333' },
]

// 解
function r(arr) {
  let stack = arr.map((o) => ({ ...o, index: 1 }))
  const ret = []
  let obj = {}
  let depth = 1
  while (stack.length) {
    const top = stack.pop()
    if (top.index === 1) {
      obj = {}
      depth = 1
    }
    obj[`code${depth}`] = top.code
    if (top.children.length) {
      stack = stack.concat(top.children)
      depth++
    } else {
      ret.push({ ...obj })
    }
  }
  return ret
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
Last Updated: 5/5/2021, 10:57:43 PM