JS中的递归示例


原始数据

let res = [
  // 一级
  {
    indexCode: 'root00',
    name: '总区域',
    parentIndexCode: '-1',
  },
  // 二级
  {
    indexCode: 'A-01',
    name: 'A区域-01',
    parentIndexCode: 'root00',
  },
  {
    indexCode: 'B-01',
    name: 'B区域-01',
    parentIndexCode: 'root00',
  },
  // 三级
  {
    indexCode: 'A-01-01',
    name: 'A区域-01-01',
    parentIndexCode: 'A-01',
  },
  {
    indexCode: 'A-01-02',
    name: 'A区域-01-02',
    parentIndexCode: 'A-01',
  },
  // 四级
  {
    indexCode: 'A-01-01-01',
    name: 'A区域-01-01-01',
    parentIndexCode: 'A-01-01',
  },
];

递归函数

function createTree(arr, parentIndex) {
  let treeData = [];
  arr.forEach(item => {
    if (parentIndex == item.parentIndexCode) {
      item.children = createTree(arr, item.indexCode);
      treeData.push(item);
    }
  });
  return treeData;
};

递归结果

let data = createTree(res, 'root00');
console.log(data);

// 结果
[
  {
    indexCode: "A-01",
    name: "A区域-01",
    parentIndexCode: "root00",
    children: [
      {
        indexCode: "A-01-01",
        name: "A区域-01-01",
        parentIndexCode: "A-01",
        children: [
          {
            indexCode: "A-01-01-01",
            name: "A区域-01-01-01",
            parentIndexCode: "A-01-01",
            children: []
          }
        ]
      },
      {
        indexCode: "A-01-02",
        name: "A区域-01-02",
        parentIndexCode: "A-01",
        children: []
      }
    ]
  },
  {
    indexCode: "B-01",
    name: "B区域-01",
    parentIndexCode: "root00",
    children: []
  }
]

  目录