【问题标题】:How to convert an array of URLs into a tree/folder structure data?如何将 URL 数组转换为树/文件夹结构数据?
【发布时间】:2021-04-04 11:22:27
【问题描述】:

首先,我有一组使用simple-crawler 库抓取的网址。

接收到的数据就是我要转换成树形结构或者文件夹结构的。 我在这里使用react-tabulator,因为我想调整表格列的大小。 现在与普通表一起,我想要嵌套的文件夹视图结构。

//input data
const urls = [
   { id: 1, address: 'https://happy.com' },
   { id: 2, address: 'https://happy.com/about' },
   { id: 3, address: 'https://happy.com/contact' },
   { id: 4, address: 'https://happy.com/contact/office' },
   { id: 5, address: 'https://happy.com/contact/home' },
   { id: 6, address: 'https://happy.com/projects' },
];

//output data
tableDataNested = [
  { id: 1, address: 'https://happy.com', 
    _children:[
      { id: 2, address: 'https://happy.com/about', _children:[] },
      { id: 3, address: 'https://happy.com/contact',
        _children:[
          { id: 4, address: 'https://happy.com/contact/office', _children:[] },
          { id: 5, address: 'https://happy.com/contact/home', _children:[] },
        ] 
      },
      { id: 6, address: 'https://happy.com/projects', _children:[] },
    ] 
  } 
];

虽然我看到了 1-2 篇类似这个概念的帖子,但我不确定纯 JS 的做法,或者也可能使用一些不错的库。 有什么见解吗?

【问题讨论】:

    标签: javascript arrays reactjs html-table


    【解决方案1】:

    在我回答这个问题之前,我必须给出一个公平的警告,这个问题很宽泛,版主通常会标记它们。

    幸运的是,您正在寻找的解决方案也在 UI 设计术语中称为“树”。我找到了一些:

    希望,这会有所帮助。

    【讨论】:

      【解决方案2】:

      您可以将 URL-s 沿最后一个斜线拆分(由于//: 部分,此处总是会有一个)并使用Map 来跟踪包含关系:

      const urls = [
         { id: 1, address: 'https://happy.com' },
         { id: 2, address: 'https://happy.com/about' },
         { id: 3, address: 'https://happy.com/contact' },
         { id: 4, address: 'https://happy.com/contact/office' },
         { id: 5, address: 'https://happy.com/contact/home' },
         { id: 6, address: 'https://happy.com/projects' },
      ];
      
      const tableDataNested = [];
      const prefixmap = new Map();
      for(let url of urls) {
         url._children = [];                        // extend node with the array
         let address = url.address;
         let lastslash = address.lastIndexOf('/');
         let prefix = address.substring(0,lastslash);
         if(prefixmap.has(prefix)) {                // has parent, so add to that one
            prefixmap.get(prefix)._children.push(url)
         } else {                                   // toplevel node
            tableDataNested.push(url);
         }
         prefixmap.set(address,url);                // store as potential parent in any case
      }
      console.log(tableDataNested);

      这个 sn-p 实际上修改了原始对象(在 urls 中),但当然也可以根据需要制作副本,例如

      url = {id:url.id,address:url.address,_children:[]};
      

      而不是url._children = [];

      【讨论】:

        猜你喜欢
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        • 2018-08-03
        • 1970-01-01
        相关资源
        最近更新 更多