{
"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”的绝对路径。但是每个子目录/目录都缺少“路径”值。每个具有path=null的子目录都需要根据定义了绝对路径的最深子目录(type=“file”)分配路径(预期输出被注释为//应计算为:)。
我尝试了迭代方法,但问题是我必须从深度遍历json到顶部(即。最深沉的孩子对父母)。有人能推荐更清洁的方法吗?
发布于 2019-10-23 17:02:56
如果存在并交出最后一条路径,您可以通过使用path属性和迭代children来设置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; }
发布于 2019-10-23 17:07:42
你可以试试这个,
function setPath(obj,path){
let currentPath=path+'/'+obj.name;
obj.path=currentPath;
if(obj.children && obj.children.length){
obj.children.forEach(item=>this.setPath(item,currentPath))
}
}用'/‘(如setPath(obj,'/') )的对象和路径名称调用此函数
https://stackoverflow.com/questions/58527676
复制相似问题