我有以下列表:
[
{'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中没有。
我需要一份树的列表。
提前感谢
发布于 2018-10-19 06:06:10
此代码可以帮助您:
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));
发布于 2018-10-19 03:34:33
我写这篇文章是为了从一个单词列表中创建一个Trie。您可能会根据您的目的对其进行调整:
const sortLetters = (string) => {
// I'm using a space as a key here because it is the only letter that cannot by any definition be construed as a letter constituting a word.
let obj = {' ': "\n"};
for (let i = string.length - 1 ; i >= 0 ; i--) {
const tmp = {};
tmp[string[i]] = obj;
obj = tmp;
}
return obj;
}
const wordMap = {};
console.time("Build trie");
allWords.forEach(function(value){_.merge(wordMap, sortLetters(value))});
console.timeEnd("Build trie");
console.log(wordMap);
https://stackoverflow.com/questions/52881238
复制相似问题