Urls / Array to Tree список в JavaScript - PullRequest
0 голосов
/ 18 октября 2018

У меня есть следующий список:

[
  {'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 голосов
/ 19 октября 2018

Этот код может вам помочь:

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));
0 голосов
/ 18 октября 2018

Я написал это, чтобы создать 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...