循环到对象中的文件系统结构以获取所有文件 [英] Loop to a filesystem structure in my object to get all the files
问题描述
我从服务器上获得了一个Javascript对象,该对象描述了一个文件系统.现在我想获取系统中所有文件的路径,例如树的端点.
I get a Javascript Object from my server, which depicts a filesystem. Now I want to get the path of all files in the system, e.g. the endpoints of the tree.
文件结构示例:
└── pages
└── services
└── project
│── headline
│── test
│ └── text
│ └── picture
│── text
可读JSON:
{
"path":"/pages/services/project",
"is_dir":true,
"children":[
{
"path":"/pages/services/project/headline",
"is_dir":false,
"children":[
]
},
{
"path":"/pages/services/project/text",
"is_dir":false,
"children":[
]
},
{
"path":"/pages/services/project/test/",
"is_dir":true,
"children":[
{
"path":"/pages/services/project/test/text",
"is_dir":false,
"children":[
]
},
{
"path":"/pages/services/project/test/picture",
"is_dir":false,
"children":[
]
}
]
}
]}
预期输出:
/pages/services/project/headline
/pages/services/project/text
/pages/services/project/test/text
/pages/services/project/test/picture
我稍微递归地玩了一下,做了一个愚蠢的功能,当一个dir只有一个孩子时,该功能可以工作.我的问题是我无法掌握处理更多孩子的方法.有没有办法遍历每个孩子?
I played around a little bit with recursion and made a dumb function that works when a dir has only one child. My Problem is that I can`t grasp a way to handle more children. Is there a way to iterate over every child?
这是我的代码:
var json = {"path":"/pages/services/project", "is_dir":true, "children":[{"path":"/pages/services/project/headline","is_dir":false,"children":[]},{"path":"/pages/services/project/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/","is_dir":true,"children":[{"path":"/pages/services/project/test/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/picture","is_dir":false,"children":[]}]}]};
json.children.forEach(function (child) {
out(goToDeepestPoint(child).path);
});
function goToDeepestPoint(node) {
if (node.is_dir)
return goToDeepestPoint(node.children[0]);
else
return node;
}
function out()
{
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
<pre id="output"></pre>
推荐答案
我正忙于解决您的原始问题,并使其正常工作:
I was busy having a play with your original question and got this working:
goToDeepestPoint(json);
function goToDeepestPoint(node) {
if (node.is_dir)
node.children.forEach(function (child) {
goToDeepestPoint(child);
});
else
return out(node.path);
}
根据您的编辑可能不适当,但浪费它可耻!
May not be appropriate in the light of your edit, but shame to waste it!
这篇关于循环到对象中的文件系统结构以获取所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!