I have the list of URL like below. How to convert it into complete json object?
My array of URLs.
[
"path1/subpath1/file1.doc","path1/subpath1/file2.doc","path1/subpath2/file1.doc","path1/subpath2/file2.doc","path2/subpath1/file1.doc","path2/subpath1/file2.doc","path2/subpath2/file1.doc","path2/subpath2/file2.doc","path2/subpath2/additionalpath1/file1.doc"
]
I want this as json object like:
{
"path1":{
"subpath1":["file1.doc","file2.doc"],
"subpath2":["file1.doc","file2.doc"]
},
"path2":{
"subpath1":["file1.doc","file2.doc"],
"subpath2":["file1.doc","file2.doc"],
"additionalpath1":{
"additionalpath1":["file1.doc"]
}
}
}
How to do this?
I tried it with the below code snippets. But there are few folder objects are missing.
If you try this code you will find that test1 and additional objects are missing:
<html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p id="demo"></p>
<script>
let paths = [ "admin/640954.jpg", "admin/test1/3m-nd.jpg",
"admin/test1/Acct.png", "admin/test1/additional/111.gif", "admin/test1/additional/Aard.jpg",
"dp/151292.jpg", "dp/151269.jpg", "dp/1515991.jpg" ];
function getMap(urls){
var map = {};
urls.forEach(function(url){
var parts = url.split("/");
makePath(map, parts);
})
return map;
}
function makePath(map,parts){
var currentPath = map;
for(var i = 0 ; i < parts.length - 1 ; i++ ){
if(i == parts.length -2 ){
currentPath[parts[i]] = currentPath[parts[i]] || [];
currentPath[parts[i]].push(parts[++i]);
}else{
currentPath[parts[i]] = currentPath[parts[i]] || {};
currentPath = currentPath[parts[i]];
}
}
}
document.getElementById("demo").innerHTML=JSON.stringify(getMap(paths));
</script>
</body>
</html>