我正在尝试将表示我的文件系统的嵌套对象转换为表示每个文件夹和文件的文件路径的字符串数组。
输入:
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);
最佳答案
这是一个工作版本:
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));
所以我保留了你的大部分代码,但改变了一个事实,即当你保留“旧”键时,我保留了当前路径,它作为所有文件的前缀和所有目录的前缀将附加当前 key 。
关于javascript - 从 Javascript 中的嵌套对象创建字符串路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663402/