我有一个如下所示的数组,其中有两种类型的数据,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"
}
]
}
];
想要的结果是
[
{
"id": 3,
"type": "file",
"url": "www.first.com"
}, {
"id": 4,
"type": "file",
"url": "www.second.com"
}, {
"id": 6,
"type": "file",
"url": "www.third.com"
}
]
注意:可以有多个级别,例如内部文件夹项目,也可以有另一个文件夹
任何帮助将不胜感激。谢谢!
最佳答案
假设您的文件夹结构可能跨越几个层次,您可能需要递归遍历输入数组以展平树结构,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))
.as-console-wrapper {min-height:100%;}
关于javascript - 展平多级文件夹树结构,在输出中仅保留 'file' 类型的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62404275/