javascript - 基于 JSON 对象数组创建嵌套 JSON

标签 javascript json

我有一个 JSON 对象数组,类似于:

var fileArray = [
  { name: "file1", path: "/main/file1" },
  { name: "file2", path: "/main/folder2/file2" },
  { name: "file4", path: "/main/folder3/file4" },
  { name: "file5", path: "/main/file5" },
  { name: "file6", path: "/main/file6" }
];  

我希望它最终看起来像:

fileTree = [
  {
    "name": "file1",
    "children": []
  },
  {
    "name": "folder1"
    "children": [
      {
        "name": "folder2",
        "children": [
          {
            "name": "file2",
            "children": []
          }
        ]
      },
      {
        "name": "folder3",
        "children": [
          {
            "name": "file4",
            "children": []
                }
              ]
            }
          ]
        },
  {
    "name": "file5",
    "children": []
        },
  {
    "name": "file6",
    "children": []
  }
];

我尝试了Create a nested UL menu based on the URL path structure of menu items中提到的解决方案但对第一个答案的第一个评论正是我遇到的问题。感谢所有帮助。

最佳答案

您可以使用嵌套哈希表作为对相同目录的引用,并以相同的方式构建结果集。

var fileArray = [{ name: "file1", path: "/main/file1" }, { name: "file2", path: "/main/folder2/file2" }, { name: "file4", path: "/main/folder3/file4" }, { name: "file5", path: "/main/file5" }, { name: "file6", path: "/main/file6" }],
    temp = [],
    fileTree;

fileArray.forEach(function (hash) {
    return function (a) {
        a.path.replace('/', '').split('/').reduce(function (r, k) {
            if (!r[k]) {
                r[k] = { _: [] };
                r._.push({ name: k, children: r[k]._ });
            }
            return r[k];
        }, hash);
    };
}({ _: temp }));

fileTree = temp[0].children;
console.log(fileTree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 基于 JSON 对象数组创建嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308575/

相关文章:

javascript - 确定在 react 中选中的复选框的方法(useState)

javascript - Ajax & PHP - 如何在数据插入弹出新页面后立即触发 window.open

javascript - jQuery.Deferred 异常 : Cannot read property 'split' of null TypeError: Cannot read property 'split' of null

python - 从 CSV 创建特定格式的 JSON 文件

python - 将多嵌套的 dict/json 加载到 pandas 中

javascript - 如何忽略 Angular 路径中的 '#' 字符?

javascript - 是否可以在Java中使用类似于JS回调的东西?

json - 使用 NSURLSession 时如何访问数据?

json - BASH JQ 命令

javascript - 将 JSON 属性转换为 int php