将树结构展平为数组

flatten tree structure into array

我有这个树结构:

    data = 
    {
     [
       {
        type: "folder"
        name: "animals"
        path: "/animals"
        children  :
          [
            {
            type: "folder"
            name: "cat"
            path: "/animals/cat"
            children:
              [
                {
                  type: "folder"
                  name: "images"
                  path: "/animals/cat/images"
                  children: 
                    [
                      {
                        type: "file"
                        name: "cat001.jpg"
                        path: "/animals/cat/images/cat001.jpg"
                      },
                      {
                        type: "file"
                        name: "cat001.jpg"
                        path: "/animals/cat/images/cat002.jpg"
                      }
                    ]
                }
              ]
            }
        ]
      }
    ]
}

我想把它变成

[
  {
    type: "folder"
    name: "animals"
    path: "/animals"
  },
  {
    type: "folder"
    name: "cat"
    path: "/animals/cat"
  },
  {
    type: "folder"
    name: "images"
    path: "/animals/cat/images"
  },
  {
    type: "file"
    name: "cat001.jpg"
    path: "/animals/cat/images/cat001.jpg"
  },
  {
    type: "file"
    name: "cat001.jpg"
    path: "/animals/cat/images/cat002.jpg"
  }
]

我想出了这个功能,但是好像不行

    function flatten(nodes, flattedNodes) {
      for (let index = 0; index < nodes.length; index++) {
        flattedNodes.push(nodes[index]);
        if (nodes[index].children !== undefined)
        if (nodes[index].children.length > 0)
          flatten(nodes[index].children, flattedNodes);
      }
    }

  let flattedTree = [];
  flatten(data, flattedTree);

  console.log(JSON.stringify(flattedTree, null, 4));

它不会展平某些元素。有什么解决办法吗?

这是一个使用 flatMap() 和递归的解决方案:

const flatten = (array) => array.flatMap(({ type, name, path, children }) => [
  { type, name, path },
  ...flatten(children || [])
]);

完整片段:

const data = [{
  type: "folder",
  name: "animals",
  path: "/animals",
  children: [{
    type: "folder",
    name: "cat",
    path: "/animals/cat",
    children: [{
      type: "folder",
      name: "images",
      path: "/animals/cat/images",
      children: [{
          type: "file",
          name: "cat001.jpg",
          path: "/animals/cat/images/cat001.jpg"
        }, {
          type: "file",
          name: "cat001.jpg",
          path: "/animals/cat/images/cat002.jpg"
        }
      ]
    }]
  }]
}];

const flatten = (array) => array.flatMap(({type, name, path, children}) => [
  { type, name, path },
  ...flatten(children || [])
]);

console.log(flatten(data));