JS数组结构转化成树型结构

220 阅读1分钟

前言

日常开发中会遇到转换为树型结构的需求,如路由列表的处理。

一、输入

const arr = [
  { id: 1, title: 'child1', parentId: 0 },
  { id: 2, title: 'child2', parentId: 0 },
  { id: 3, title: 'child1_1', parentId: 1 },
  { id: 4, title: 'child1_2', parentId: 1 },
  { id: 5, title: 'child2_1', parentId: 2 },
  { id: 6, title: 'child2_1_1', parentId: 5 }
];

二、输出

const tree= [
  {
    id: 1,
    title: 'child1',
    parentId: 0,
    children: [
      { id: 3, title: 'child1_1', parentId: 1 },
      { id: 4, title: 'child1_2', parentId: 1 }
    ]
  },
  {
    id: 2,
    title: 'child2',
    parentId: 0,
    children: [
      {
        id: 5,
        title: 'child2_1',
        parentId: 2,
        children: [{ id: 6, title: 'child2_1_1', parentId: 5 }]
      }
    ]
  }
];

三、实现方法

function formatTree(list) {
  const parent = list.filter((e) => e.parentId === 0);
  const child = list.filter((e) => e.parentId !== 0);
  function dataToTree(parent, child) {
    parent.forEach((p) => {
      child.forEach((c) => {
        if (p.id === c.parentId) {
          const _children = JSON.parse(JSON.stringify(child)).filter((e) => e.id !== c.id);
          dataToTree([c], _children);
          p['children'] = p.children ? [...p.children, c] : [c];
        }
      });
    });
  }
  dataToTree(parent, child);
  return parent;
}