JavaScript中的Urls / Array to Tree列表

时间:2018-10-18 19:31:22

标签: javascript recursion tree

我有以下列表:

[
  {'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中却找不到。

我需要获取一个树形列表。

预先感谢

2 个答案:

答案 0 :(得分:1)

我写这篇文章是为了从单词列表创建一个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);

答案 1 :(得分:1)

此代码可以为您提供帮助:

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));