当一个数组有children,且层级很深的时候,怎样将children数据拿出来?

img

举个例子,如何输出


 [{1},{2},{3},{4},{5},{6}]

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let arr = [
        {
          id: 1,
          children: [
            {
              id: 2,
              children: null,
            },
            {
              id: 3,
              children: [
                {
                  id: 4,
                  children: null,
                },
              ],
            },
          ],
        },
        {
          id: 5,
          children: [
            {
              id: 6,
              children: null,
            },
          ],
        },
      ];

      function recursionArray(arr) {
        let result = [];
        arr.forEach((item) => {
          result.push({ id: item.id });
          if (item.children) {
            result = [...result, ...recursionArray(item.children)];
          }
        });
        return result;
      }

      console.log("recursionArray", recursionArray(arr));
    </script>
  </body>
</html>

用递归拿
let result=[]
function get(arr){
arr.forEach(item=>{
result.push(item.id);
if(children){
get(children)
}else{
return
}
})
}

手敲的,可能有问题,思路没错