Javascript 如何将URL数组转换为树/文件夹结构数据?
首先,我有一个URL数组,我使用库对其进行了爬网 接收到的数据是我想要转换为树结构或文件夹结构的数据。 我之所以使用这里,是因为我想调整表的列大小。 现在,除了普通表之外,我还希望有嵌套的文件夹视图结构Javascript 如何将URL数组转换为树/文件夹结构数据?,javascript,arrays,reactjs,html-table,Javascript,Arrays,Reactjs,Html Table,首先,我有一个URL数组,我使用库对其进行了爬网 接收到的数据是我想要转换为树结构或文件夹结构的数据。 我之所以使用这里,是因为我想调整表的列大小。 现在,除了普通表之外,我还希望有嵌套的文件夹视图结构 //input data const urls = [ { id: 1, address: 'https://happy.com' }, { id: 2, address: 'https://happy.com/about' }, { id: 3, address: 'http
//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的做法,或者可能也使用了一些不错的库。
任何人有什么见解吗?在我回答这个问题之前,我必须给出一个公平的警告,这个问题很广泛,主持人通常会标记它们 幸运的是,您正在寻找的解决方案在UI设计术语中也被称为“树”。我发现了一些:
-
- 这里的问题是,您必须使用
库来实现这一点(我的假设)材质ui
- 这里的问题是,您必须使用
-
- 这一个也有一个页面&一个活生生的工作示例
- 另一个,
希望,这会有所帮助。您可以沿着最后一条斜线拆分URL-s(由于
/:
部分的原因,此处始终会有一条),并使用映射来跟踪包含关系:
const URL=[
{id:1,地址:'https://happy.com' },
{id:2,地址:'https://happy.com/about' },
{id:3,地址:'https://happy.com/contact' },
{id:4,地址:'https://happy.com/contact/office' },
{id:5,地址:'https://happy.com/contact/home' },
{id:6,地址:'https://happy.com/projects' },
];
const tableDataNested=[];
const prefixmap=新映射();
for(让url的url){
url._children=[];//使用数组扩展节点
让address=url.address;
设lastslash=address.lastIndexOf('/');
让前缀=address.substring(0,lastslash);
如果(prefixmap.has(prefix)){//有父项,那么添加到该父项
prefixmap.get(前缀)。\u children.push(url)
}else{//顶级节点
tableDataNested.push(url);
}
prefixmap.set(地址,url);//在任何情况下都存储为潜在的父级
}
log(tableDataNested)代码>