求教将平铺数据转为树形结构算法(javascript实现)

已知数据:
const datas = [
{ name: 'A/B/C' },
{ name: 'D/E/F' },
{ name: 'D/E/G' },
{ name: 'D/E/H' },
{ name: 'D/E/I' },
{ name: 'D/E/J' },
{ name: 'A1/B2/C3/D4' },
{ name: 'E5' },
];
求教算法将以上数据转化为以下树形数据结构:
const treeData = [
{

label: 'A',
value: 'A',
children: [
  {
    label: 'B',
    value: 'B',
  },
],

},
{

label: 'D',
value: 'D',
children: [
  {
    label: 'E',
    value: 'E',
    children: [
      {
        label: 'F',
        value: 'G',
      },
      {
        label: 'H',
        value: 'H',
      },
      {
        label: 'I',
        value: 'I',
      },
    ],
  },
],

},
{

label: 'A1',
value: 'A1',
children: [
  {
    label: 'B2',
    value: 'B2',
    children: [
      {
        label: 'C3',
        value: 'C3',
        children: [
          {
            label: 'D4',
            value: 'D4',
          },
        ],
      },
    ],
  },
],

},
{

label: 'E5',
value: 'E5',

},
];

阅读 458
评论 2019-10-10 提问
    1 个回答
    评论 赞赏 2019-10-10