我尝试将表示文件系统的嵌套对象转换为表示每个文件夹和文件的文件路径的字符串数组。
输入:
let obj = {
'app': {
'body': {
'abs': {
'muscles.txt': 1
},
'foot.js': 1,
'hand.txt': 1,
'leg.txt': 1
},
'cat.txt': 1,
'dog.js': 1,
'writing': {
'pen.txt': 1,
'phone.txt': 1
}
}
};
输出:
[
'/app',
'/app/body',
'/app/body/abs/',
'/app/body/abs/muscles.txt',
'/app/body/foot.js',
'/app/body/hand.txt',
...
]
到目前为止我所拥有的(它不起作用):
function filePaths(obj, oldKey = '', store = []) {
for (let key in obj) {
if (typeof obj[key] === 'object') {
store.push('/' + key);
filePaths(obj[key], key, store);
} else {
store.push('/' + oldKey + '/' + key);
}
}
return store;
}
filePaths(obj);
发布于 2018-08-03 07:51:12
以下是一个工作版本:
let obj = {
'app': {
'body': {
'abs': {
'muscles.txt': 1
},
'foot.js': 1,
'hand.txt': 1,
'leg.txt': 1
},
'cat.txt': 1,
'dog.js': 1,
'writing': {
'pen.txt': 1,
'phone.txt': 1
}
}
};
function filePaths(obj, prefix = '', store = []) {
for (let key in obj) {
const curPath = `${prefix}/${key}`;
if (typeof obj[key] === 'object') {
store.push(curPath);
filePaths(obj[key], curPath, store);
} else {
store.push(curPath);
}
}
return store;
}
console.log(filePaths(obj));
所以我保留了你的大部分代码,但改变了这样一个事实,即当你保留“旧”键时,我保留了当前路径,它作为所有文件的前缀,并作为将获得当前键的所有目录的前缀。
发布于 2018-08-03 07:45:32
在递归方面,您走在了正确的道路上。对于每个调用,循环遍历当前对象中的每个属性,为该属性创建路径并将其添加到结果数组中。如果这个属性指向一个对象,那么它就是一个非终结点节点,并被递归地调用,为它的子节点添加路径。
const pathify = (o, res=[], path=[]) => {
for (const dir in o) {
const s = path.join("/");
res.push(`/${s ? `${s}/${dir}` : dir}`);
if (typeof o[dir] === "object") {
pathify(o[dir], res, path.concat(dir));
}
}
return res;
};
const obj = {
'app': {
'body': {
'abs': {
'muscles.txt': 1
},
'foot.js': 1,
'hand.txt': 1,
'leg.txt': 1
},
'cat.txt': 1,
'dog.js': 1,
'writing': {
'pen.txt': 1,
'phone.txt': 1
}
}
};
console.log(pathify(obj));
发布于 2018-08-03 07:55:07
下面是一个递归解决方案,它利用了带有扩展运算符、concat
和map
的Object.keys
方法
let obj = {
'app': {
'body': {
'abs': {
'muscles.txt': 1
},
'foot.js': 1,
'hand.txt': 1,
'leg.txt': 1
},
'cat.txt': 1,
'dog.js': 1,
'writing': {
'pen.txt': 1,
'phone.txt': 1
}
}
};
function filePaths(obj, prefix = "", store = []) {
if (typeof obj !== "object") return [prefix];
return (prefix && [prefix] || []).concat(...Object.keys(obj).map(k => filePaths(obj[k], prefix + "/" + k, store)))
}
console.log(filePaths(obj))
https://stackoverflow.com/questions/51663402
复制相似问题