英文:
Convert list of file paths to a json in ReactJS
问题
以下是翻译好的代码部分:
我正在尝试构建一个将路径列表转换为以下对象的函数;脚本的输出应该结构如下。
输出
```python
data = [
{
"type": "folder",
"name": "dir1",
"children": [
{
"type": "folder",
"name": "photos",
"children": [
{
"type": "file",
"name": "mydir1.pdf",
},
{
"type": "file",
"name": "yourdir1.pdf",
}
]
}
]
}
而输入如下
paths = [
"dir1/photos/mydir1.pdf",
"dir1/photos/yourdir1.pdf"
]
这是代码的翻译部分,不包括问题或其他内容。
<details>
<summary>英文:</summary>
I am trying to build a function that converts a list of paths into a object as below; the output of the script should be structured as below.
Output
data = [
{
"type": "folder",
"name": "dir1",
"children": [
{
"type": "folder",
"name": "photos",
"children": [
{
"type": "file",
"name": "mydir1.pdf",
},
{
"type": "file",
"name": "yourdir1.pdf",
}
]
}
]
}
And input is like this
paths = [
"dir1/photos/mydir1.pdf",
"dir1/photos/yourdir1.pdf"
]
</details>
# 答案1
**得分**: 1
以下是翻译好的代码部分:
```javascript
function buildTree(paths) {
const tree = [];
for (let path of paths) {
const pathParts = path.split('/');
let subtree = tree;
for (let i = 0; i < pathParts.length; i++) {
const part = pathParts[i];
const isFolder = i < pathParts.length - 1;
let node = subtree.find(n => n.name === part);
if (!node) {
node = {
type: isFolder ? 'folder' : 'file',
name: part,
children: isFolder ? [] : undefined
};
subtree.push(node);
}
if (isFolder) {
subtree = node.children;
}
}
}
return tree;
}
英文:
You can try below function:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function buildTree(paths) {
const tree = [];
for (let path of paths) {
const pathParts = path.split('/');
let subtree = tree;
for (let i = 0; i < pathParts.length; i++) {
const part = pathParts[i];
const isFolder = i < pathParts.length - 1;
let node = subtree.find(n => n.name === part);
if (!node) {
node = {
type: isFolder ? 'folder' : 'file',
name: part,
children: isFolder ? [] : undefined
};
subtree.push(node);
}
if (isFolder) {
subtree = node.children;
}
}
}
return tree;
}
<!-- end snippet -->
答案2
得分: 0
你可以使用对象引用来构建树。
const final = { result: [] };
for (const path of paths) {
let context = final;
for (const name of path.split("/")) {
if (!context[name]) {
context[name] = { result: [] };
let type = "folder";
if (name.endsWith(".pdf")) {
type = "file";
}
context.result.push({ name, type, children: context[name].result });
}
context = context[name];
}
}
console.log(final.result);
如果你需要进一步的帮助,请随时告诉我。
英文:
You can build tree with the help of object reference.
const final = {result: []};
for (const path of paths) {
let context = final;
for (const name of path.split("/")) {
if (!context[name]) {
context[name] = { result: [] };
let type = "folder";
if (name.endsWith(".pdf")) {
type = "file";
}
context.result.push({name, type, children: context[name].result})
}
context = context[name];
}
}
console.log(final.result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论