【问题标题】:Create a tree from a list of strings containing paths从包含路径的字符串列表创建树
【发布时间】:2020-10-02 18:09:15
【问题描述】:

请参阅下面的编辑

我想尝试从路径列表中创建一棵树,并在另一个问题的 stackoverflow 上找到此代码,它似乎工作正常,但我想删除空的子数组,而不是让它们显示为零项。

我尝试计算 r[name].result 长度并仅在大于零时推送它,但我最终在任何节点上都没有子节点。

let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];

let result = [];
let level = {result};

paths.forEach(path => {
  path.split('/').reduce((r, name, i, a) => {
    if(!r[name]) {
      r[name] = {result: []};
      r.result.push({name, children: r[name].result})
    }
    
    return r[name];
  }, level)
})

console.log(result)

编辑 我不想直接询问我使用它的目的,但如果它有助于我尝试创建一个这样的数组:(这是从 ng-zorro cascader 需要的配置的复制粘贴)

const options = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [
      {
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [
          {
            value: 'xihu',
            label: 'West Lake',
            isLeaf: true
          }
        ]
      },
      {
        value: 'ningbo',
        label: 'Ningbo',
        isLeaf: true
      }
    ]
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [
      {
        value: 'nanjing',
        label: 'Nanjing',
        children: [
          {
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
            isLeaf: true
          }
        ]
      }
    ]
  }
];

来自这样的平面字段数组:

let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];

【问题讨论】:

    标签: javascript path tree


    【解决方案1】:

    我建议使用不同的方法。

    这种方法采用对象而不是数组来达到更深层次,并且仅在需要嵌套级别时才分配数组。

    let paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
        result = paths
            .reduce((parent, path) => {
                path.split('/').reduce((r, name, i, { length }) => {
                    let temp = (r.children ??= []).find(q => q.name === name);
                    if (!temp) r.children.push(temp = { name, ...(i + 1 === length && { isLeaf: true }) });
                    return temp;
                }, parent);
                return parent;
            }, { children: [] })
            .children;
    
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 感谢您的回复... ??= 在 JS 中的作用。我认为我以前从未见过它,在这一行: let temp = (r.children ??= []).find(q => q.name === name);
    • 谢谢,它工作得很好(在更新打字稿以支持逻辑无效之后)。
    • Nina,当孩子为空/失踪时,有没有办法修改它以添加 isLeaf:true ?谢谢
    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2021-07-12
    相关资源
    最近更新 更多