我在编写算法时遇到了困难。上下文如下:我有一个路径数组,我想放在一个对象中,比如重建一个文件树。
以下是一个简单的示例:
var paths = [
'/var/log/log.txt',
'/var/log/test.txt',
'/home/toto/someFile.txt',
'/wtf.txt'
];
我希望这一系列路径成为像这样的对象:
var tree = {
var: {
log: ['log.txt', 'test.txt']
},
home: {
toto: ['someFile.txt']
},
wtf.txt: null // I don't know how to handle this case
};
有关如何做这样的事情的任何提示?
实际上,我有类似的东西,但它最终只有一个深度级别,而不是在根级别处理文件:
function rebuildTree(paths, tree) {
paths.forEach(function (path) {
var splittedPath;
if (path.indexOf("/") > -1) {
splittedPath = path.split('/');
} else {
splittedPath = [path];
}
splittedPath.some(function(item, index) {
if (!tree.hasOwnProperty(item) && index > 0) {
tree[item] = {};
}
if ((parseInt(index) + 1) <= (splittedPath.length - 1)) {
var nextIndex = parseInt(index + 1);
var nextPath = splittedPath.splice(0, index);
tree[item] = rebuildTree(nextPath, tree[item]);
}
});
});
}
答案 0 :(得分:0)
我在下面编写了一个小帮助函数,应该可以轻松完成,检查注释以查看它是如何工作的(请参阅控制台输出)。
UIPickerView
这方面的一个重大缺点是,由于你想拥有的结构,它会中断。一个更好的解决方案就是以下内容,它可以降低复杂性并使其更容易理解:
CoreData
在此代码段中,所有路径都只是嵌套键,您可以使用function treeify(paths){
// This will store our tree
var tree = {};
// This will run through all our paths
paths.forEach(function(path){
// This will remove the initial slash
if(path.indexOf('/') === 0) path = path.substring(1);
// Find all the individual files/folders
path = path.split('/');
// If there is only one we'll assume its a file and assign your `null`
if(path.length === 1){
tree[path[0]] = tree[path[0]] || null;
return;
}
// Create a variable that will store the current branch we are in
var branch = tree[path[0]] = tree[path[0]] || {};
// Loop through the remaining values, repointing the branch as we go.
for(var i = 1; i < path.length; i++){
// The second to last item will need to be an array (as suggested).
if(i === path.length-2)
branch = branch[path[i]] = branch[path[i]] || [];
// The last item will be pushed to the array (as suggested).
else if(i === path.length-1)
branch.push(path[i]);
// All others will simply create a new branch.
else
branch = branch[path[i]] = branch[path[i]] || {};
}
});
return tree;
}
console.log(treeify([
'/var/log/log.txt',
'/var/log/test.txt',
'/home/toto/someFile.txt',
'/wtf.txt'
]));
构造来查找内容。它不太方便,但以数组结尾可能会导致以下问题:当您有两条路径,一条为function treeify(paths){
var tree = {};
paths.forEach(function(path){
if(path.indexOf('/') === 0) path = path.substring(1);
path = path.split('/');
var branch = tree[path[0]] = tree[path[0]] || {};
for(var i = 1; i < path.length; i++){
branch = branch[path[i]] = branch[path[i]] || {};
}
});
return tree;
}
console.log(treeify([
'/var/log/log.txt',
'/var/log/test.txt',
'/home/toto/someFile.txt',
'/wtf.txt'
]));
而另一条为for..in
时,推送将中断,阵列将失败。这意味着您只能有一个深度级别,而此功能可以具有任何深度级别。