TypeScript 树扁平化

TypeScript 树扁平化_第1张图片

let data: Array<any> = [
  {
    label: 'Node1',
    value: '0-0',
    children: [
      {
        label: 'Child Node1',
        value: '0-0-0',
      },
    ],
  },
  {
    label: 'Node2',
    value: '0-1',
    children: [
      {
        label: 'Child Node3',
        value: '0-1-0',
        disabled: true,
      },
      {
        label: 'Child Node4',
        value: '0-1-1',
      },
      {
        label: 'Child Node5',
        value: '0-1-2',
      },
    ],
  },
];

type TreeNode = {
  label: string;
  value: string;
  children?: TreeNode[];
};

const flatTreeData = (treeData: TreeNode[]): TreeNode[] => {
  const flatData: TreeNode[] = [];

  const main = (node: TreeNode): void => {
    flatData.push({
      label: node.label,
      value: node.value
    })
    
    if (node.children && node.children.length > 0) {
      node.children.forEach((item: any):void => {
        main(item)
      })
    }
  }

  treeData.forEach((item: any):void => {
    main(item)
  })

  return flatData
}

console.log(flatTreeData(data))

你可能感兴趣的:(JavaScript,TypeScript,脚本语言,typescript,javascript,前端)