JavaScript - 从对象动态生成文件路径



我已经找了几个小时,但仍然找不到任何关于它的信息,所以我在这里问。我有一个小的PHP脚本,它生成一个文件和文件夹的JSON树,然后将其作为JavaScript变量提取到客户端。结果通常如下所示:

{
"folder_name" : {
"another_folder": {
"third_folder": {
0: "some_file.txt"
1: "another_file.png"
2: "third_file.pdf"
}
}
}
}

我想要实现的内容看起来像这样:

generatePath("some_file.txt") 

这将返回:

"folder_name/another_folder/third_folder/some_file.txt"

所以我的问题是,如何仅从 JavaScript 中的对象创建指向这些文件中的任何一个的路径?有没有办法做这样的事情?

[编辑]:可悲的是,我没有任何代码可以显示了...

因此,假设输入是真正的JSON,它将解析为JS对象,这里有一些方法:

const data = {
"folder_name" : {
"another_folder": {
"third_folder": {
"0": "some_file.txt",
"1": "another_file.png",
"2": "third_file.pdf"
}
}
},
"folder_name2" : {
"0": "up_file.txt",
"another_folder2": {
"third_folder2": ["some_file2.txt", "another_file2.png", "third_file2.pdf"]
}
}
}
function generatePath(value, currentPath = '', currentObject = data) {
for (const property in currentObject) {
if (currentObject[property] === value) {
return `${currentPath}/${value}`;
}
if (typeof currentObject[property] === 'object') {
const result = generatePath(value, `${currentPath && currentPath + '/'}${property}`, currentObject[property]);
if (result) {
return result;
}
}
}
}
document.write(
generatePath("some_file.txt"), 
'<br>', 
generatePath("some_file2.txt"),
'<br>',
generatePath("up_file.txt"),
'<br>',
generatePath("no_file.txt")
);

您可以使用循环为此创建递归函数for...in该循环将以前的路径元素存储在一个数组中。

const data = {
"folder_name": {
"another_folder": {
"third_folder": {
0: "some_file.txt",
1: "another_file.png",
2: "third_file.pdf"
}
}
}
}
function generatePath(data, file) {
let result
(function getPath(obj, file, prev = []) {
for (let i in obj) {
if (typeof obj[i] == 'object') {
getPath(obj[i], file, prev.concat(i).slice())
}
if (file == obj[i]) {
result = prev.concat(obj[i]).join('/')
}
}
})(data, file)
return result;
}
console.log(generatePath(data, "third_file.pdf"))
console.log(generatePath(data, "some_file.txt"))

相关内容

  • 没有找到相关文章

最新更新