展平多级文件夹树结构,只在输出中留下“文件”类型的项目

Sag*_*iya 3 javascript

我有一个像下面这样的数组,其中有两种类型的数据,file或者folder. 我只想过滤file类型数据。

let data = [
    {
      "id": 3,
      "type": "file",
      "url": "www.first.com"
    }, {
      "id": 4,
      "type": "file",
      "url": "www.second.com"
    }, {
      "id": 5,
      "type": "folder",
      "items": [
          {
            "id": 6,
            "type": "file",
            "url": "www.third.com"
          }
       ]
    }
];
Run Code Online (Sandbox Code Playgroud)

想要的结果是

[
    {
        "id": 3,
        "type": "file",
        "url": "www.first.com"
    }, {
        "id": 4,
        "type": "file",
        "url": "www.second.com"
    }, {
        "id": 6,
        "type": "file",
        "url": "www.third.com"
    }
]
Run Code Online (Sandbox Code Playgroud)

注意:可以有多个级别,例如文件夹内的项目,也可以有另一个文件夹

任何帮助,将不胜感激。谢谢!

Yev*_*kov 5

假设您的文件夹结构可能跨越几层深,您可能需要递归遍历您的输入数组以展平树结构,Array.prototype.flatMap()可能会派上用场:

const src = [
    {
      "id": 3,
      "type": "file",
      "url": "www.first.com"
    }, {
      "id": 4,
      "type": "file",
      "url": "www.second.com"
    }, {
      "id": 5,
      "type": "folder",
      "items": [
          {
            "id": 6,
            "type": "folder",
            "items" : [
              {
                "id" : 7,
                "type" : "file",
                "ulr" : "www.third.com"
              }
            ]
          }
       ]
    }
],

    flattenArr = arr => 
      arr.flatMap(({items=[], ...rest}) => 
        rest.type == 'folder' ? flattenArr(items) : rest)
      
      
console.log(flattenArr(src))
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {min-height:100%;}
Run Code Online (Sandbox Code Playgroud)