gpt4 book ai didi

javascript - 从 JSON 目录树中的文件完整路径计算目录

转载 作者:行者123 更新时间:2023-11-29 22:46:08 25 4
gpt4 key购买 nike

{
"path": null,//should be calculated back as: "photos"
"size": 600,
"type": "directory",
"children": [
{
"path": null,//it should be calculated as: "photos/summer"
"size": 400,
"type": "directory",
"children": [
{
"path": null,//should be calculated as :"photos/summer/june"
"size": 400,
"type": "directory",
"children": [
{
"path": "photos/summer/june/windsurf.jpg",
"name": "windsurf.jpg",
"size": 400,
"type": "file",
"extension": ".jpg"
}
]
}
]
},
{
"path": null,//should be calculated as: "photos/winter"
"size": 200,
"type": "directory",
"children": [
{
"path": null,// should be calculated as: "photos/winter/january"
"size": 200,
"type": "directory",
"children": [
{
"path": "photos/winter/january/ski.png",
"name": "ski.png",
"size": 100,
"type": "file",
"extension": ".png"
},
{
"path": "photos/winter/january/snowboard.jpg",
"name": "snowboard.jpg",
"size": 100,
"type": "file",
"extension": ".jpg"
}
]
}
]
}
]
}

有一个表示目录结构的json。 json 中的所有"file"属性都有分配给属性“路径”的绝对路径。但是每个子目录/目录都缺少“路径”值。每个具有 path=null 的子目录都需要根据定义了绝对路径的最深子目录(type="file")分配路径。(预期输出注释为//应计算为:)

我尝试了迭代方法,但问题是我必须从深度到顶部遍历 json(即最深的子项朝向父项)。有人可以推荐更清洁的方法吗?

最佳答案

您可以通过获取 name 属性来设置 path 并迭代 children(如果存在)并移交最后一条路径。

function setPath(object, path = '') {
(object.children || []).forEach(o => {
var temp = setPath(o);
if (temp) object.path = temp.slice(0, temp.lastIndexOf('/'));
});
return object.path;
}

var data = { path: null, size: 600, type: "directory", children: [{ path: null, size: 400, type: "directory", children: [{ path: null, size: 400, type: "directory", children: [{ path: "photos/summer/june/windsurf.jpg", name: "windsurf.jpg", size: 400, type: "file", extension: ".jpg" }] }] }, { path: null, size: 200, type: "directory", children: [{ path: null, size: 200, type: "directory", children: [{ path: "photos/winter/january/ski.png", name: "ski.png", size: 100, type: "file", extension: ".png" }, { path: "photos/winter/january/snowboard.jpg", name: "snowboard.jpg", size: 100, type: "file", extension: ".jpg" }] }] }] };

setPath(data);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 从 JSON 目录树中的文件完整路径计算目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58527676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com