首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >javascript中的Urls/数组到树列表

javascript中的Urls/数组到树列表
EN

Stack Overflow用户
提问于 2018-10-19 03:31:22
回答 2查看 343关注 0票数 0

我有以下列表:

代码语言:javascript
复制
[
  {'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'},
]

我想要得到这样的东西:

代码语言:javascript
复制
{ 'www.example.com': 
  [ 
    { 'something': 
      [ 
        { 
          'index.htm',
          'other.htm',
          'thisthing':[
             {
               'detail.htm'
             }
          ]
        }            
      ]
    },
    { 'thatthing': 
      [ 
        { 
          'about.htm'
        }            
      ]
    },
  ]
}

我知道这是一个递归循环,需要完成这项工作,但我似乎不能正确完成它。我在C#、python和其他语言中找到了示例,但JS中没有。

我需要一份树的列表。

提前感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-19 06:06:10

此代码可以帮助您:

代码语言:javascript
复制
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));

票数 1
EN

Stack Overflow用户

发布于 2018-10-19 03:34:33

我写这篇文章是为了从一个单词列表中创建一个Trie。您可能会根据您的目的对其进行调整:

代码语言:javascript
复制
      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);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52881238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档