我有以下清单:
[
{'http://www.example.com/something/index.htm'},
{'http://www.example.com/something/other.htm'},
{'http://www.example.com/thatthing/about.htm'},
{'http://www.example.com/something/thisthing/detail.htm'},
]
我想得到这样的东西:
{ 'www.example.com':
[
{ 'something':
[
{
'index.htm',
'other.htm',
'thisthing':[
{
'detail.htm'
}
]
}
]
},
{ 'thatthing':
[
{
'about.htm'
}
]
},
]
}
我知道这是一个递归循环,需要完成此操作,但我似乎无法正确完成。我在C#,python和其他语言中找到了示例,但在JS中却找不到。
我需要一个树形清单。
提前致谢
最佳答案
此代码可以帮助您:
let data = [
'http://www.example.com/something/index.htm',
'http://www.example.com/something/other.htm',
'http://www.example.com/thatthing/about.htm',
'http://www.example.com/something/thisthing/detail.htm'
];
function map(data) {
let map = [];
data.forEach(e => merge(map, split(e)));
return map;
}
function split(href) {
let parser = document.createElement('a');
parser.href = href;
let split = [];
split.push(parser.hostname);
parser.pathname.split('/')
.filter(e => e.length > 0)
.forEach(e => split.push(e));
return split;
}
function merge(map, split) {
let e = split[0];
if (split.length === 1) {
if (map.indexOf(e) === -1)
map.push(e);
} else {
if (map.length === 0)
map[0] = {};
if (typeof map[0] !== 'object')
map.unshift({});
if (e in map[0] === false)
map[0][e] = [];
merge(map[0][e], split.slice(1));
}
}
console.log(JSON.stringify(map(data), null, 2));
关于javascript - JavaScript中的Urls/Array to Tree列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52881238/