【问题标题】:convert a flat array that has a "path" property to a nested array将具有“路径”属性的平面数组转换为嵌套数组
【发布时间】:2021-01-26 17:03:47
【问题描述】:

我有一个像这个例子一样的平面数组:

[
  {
    'name':'itemA',
    'path':'foo/bar'
  },
  {
    'name':'itemB',
    'path':'bar/foo'
  },
  {
    'name':'itemC',
    'path':'foo'
  },
  {
    'name':'itemD',
    'path':'bar'
  },
  {
    'name':'itemE',
    'path':'foo/bar/wizz'
  },
  {
    'name':'itemF',
    'path':'bar/foo'
  },
]

我想根据“路径”属性构建一棵树,所以我可以得到这个输出:

[
  {
    'name':'itemD',
    'path':'bar',
    'items':[
      {
        'name':'itemD',
        'path':'bar/foo'
      },
      {
        'name':'itemF',
        'path':'bar/foo'
      }
    ]
  },
  {
    'name':'itemC',
    'path':'foo',
    'items':[
      {
        'name':'itemA',
        'path':'foo/bar',
        'items':
        [
          {
            'name':'itemE',
            'path':'foo/bar/wizz'
          }
        ]
      },
    ]
  }
]

我怎样才能做到这一点? 我发现了一些像 this one 这样的例子,但它们是基于父 ID 而不是像我这样的“路径”。

非常感谢!

【问题讨论】:

    标签: javascript arrays multidimensional-array tree nested


    【解决方案1】:

    您可以找到关卡或为分割路径的关卡添加新对象。

    const
        data = [{ name: 'itemA', path: 'foo/bar' }, { name: 'itemB', path: 'bar/foo' }, { name: 'itemC', path: 'foo' }, { name: 'itemD', path: 'bar' }, { name: 'itemE', path: 'foo/bar/wizz' }, { name: 'itemF', path: 'bar/foo' }],
        tree = data.reduce((items, { name, path }) => {
            path.split('/').reduce((o, _, i, p) => {
                let path = p.slice(0, i + 1).join('/'),
                    temp = (o.items ??= []).find(q => q.path === path);
    
                if (!temp) o.items.push(temp = { name, path });
                return temp;
            }, { items });
            return items;
        }, []);
       
    console.log(tree);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2017-10-11
    • 2013-07-26
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    相关资源
    最近更新 更多