使用lodash将字符串数组数组转换为树对象的最有效方法是什么?

时间:2018-02-23 15:46:44

标签: javascript arrays algorithm tree lodash

我正在寻找一种方法将字符串数组(表示路径)转换为树状对象(如果可能的话,使用Lodash或纯javascript,如果它更有效)。我怀疑我们必须在里面使用一些递归函数,但我很难找到如何做到这一点。



var paths = [
  ['folder1', 'folder2', 'name1.txt'],
  ['folder1', 'folder2', 'name2.txt'],
  ['folder1', 'folder3', 'name3.txt'],
  ['folder2', 'folder4', 'name4.txt'],
  ['folder2', 'folder5', 'name5.txt'],
  ['folder2', 'folder5', 'folder6', 'name6.txt'],
  ['folder3', 'name7.txt']
];

var tree = [
  {
    name: 'folder1',
    children: [
      {
        name: 'folder2',
        children: [
          {
            name: 'name1.txt'
          },
          {
            name: 'name2.txt'
          }
        ]
      },
      {
        name: 'folder3',
        children: [
          {
            name: 'name3.txt'
          }
        ]
      }
    ]
  },
  {
    name: 'folder2',
    children: [
      {
        name: 'folder4',
        children: [
          {
            name: 'name4.txt'
          }
        ]
      },
      {
        name: 'folder5',
        children: [
          {
            name: 'name5.txt'
          },
          {
            name: 'folder6',
            children: [{ name: 'name6.txt' }]
          }
        ]
      }
    ]
  },
  {
    name: 'folder3',
    children: [{ name: 'name7.txt' }]
  }
];



var pathToTree = function(paths) {
  var tree = [];
  //... ???
  return tree;
};

pathToTree(paths);




1 个答案:

答案 0 :(得分:1)

您可以使用forEach()reduce()方法执行此操作。



var paths = [["folder1","folder2","name1.txt"],["folder1","folder2","name2.txt"],["folder1","folder3","name3.txt"],["folder2","folder4","name4.txt"],["folder2","folder5","name5.txt"],["folder2","folder5","folder6","name6.txt"],["folder3","name7.txt"]]
const result = [], tmp = {result}

paths.forEach(path => {
  path.reduce(function(r, name, i) {
    if(!r[name]) {
      const o = {name}, children = []
      r[name] = {result: children}
      if(path[i + 1]) o.children = children
      r.result.push(o)
    }
    return r[name]
  }, tmp)
})

console.log(result)