如何从打字稿中的对象列表数组中打印叶节点?

How to print the leaf nodes from an array of list of objects in typescript?

我是 typecript 的新手,在执行以下操作时遇到问题, 我有一个数组,我只想打印叶节点, 结果数组应该看起来像-['002', '004', '007'], 有人可以帮忙吗..期待学习,提前致谢!

数组-

[
        {
            Name: "A",
            HasChildren: true,
            Children: [
                {
                    Name: "002",
                    HasChildren: false,
                    Children: []
                },
                {
                    Name: "004",
                    HasChildren: false,
                    Children: []
                }
            ]
        },
        {
            Name: "007",
            HasChildren: false,
            Children: []
        }
    ]

如果数组是

[ {
                Name: "007",
                HasChildren: false,
                Children: []
  }
]

结果数组应该是 - ['007']

您可以做的是遍历每个元素。如果它没有 children,打印它并继续它的下一个兄弟。如果它确实有至少一个 child,则以相同的逻辑递归遍历每个 child。

Stackblitz:https://stackblitz.com/edit/typescript-vfvyn7?file=index.ts

const elements = [
  {
    Name: 'A',
    HasChildren: true,
    Children: [
      {
        Name: '002',
        HasChildren: false,
        Children: [],
      },
      {
        Name: '004',
        HasChildren: false,
        Children: [],
      },
    ],
  },
  {
    Name: '007',
    HasChildren: false,
    Children: [],
  },
];
console.log(elements);

function printLeaves(elements: any[]) {
  for (const element of elements) {
    if (element.Children.length == 0) {
      console.log(element);
      continue;
    }
    printLeaves(element.Children);
  }
}

printLeaves(elements)