Reputation: 85
{
"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"
}
]
}
]
}
]
}
There is a json that represents directory structure. All "file" property in json has absolute path assigned to property "path". But each sub-directories/directories is missing "path" value. Each subdirectories which have path=null needs to be assigned path on the basis of deepest child(type="file") which has absolute path defined.(Expected output is commented as //should be calculated as:)
I tried iterative approach, but problem is I have to traverse json from depth to top(ie. deepest children towards parent) . Can someone recommend cleaner approach?
Upvotes: 2
Views: 259
Reputation: 386570
You could set path
by taking name
property and iterate children
, if exist and hand over the last path.
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; }
Upvotes: 1
Reputation: 263
You can try this,
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))
}
}
call this function with the object and path name as '/'
eg setPath(obj,'/')
Upvotes: 0