Javascript无限类别深度树

时间:2014-12-25 04:19:14

标签: javascript recursion tree underscore.js

我正在尝试生成一个平面数组树,将子类别放在父类别旁边并且努力做同样的事情。

var categories = [
  {
    name: 'Javascript'
  },
  {
    name: 'jQuery',
    parent: 'Javascript'
  },
  {
    name: 'AngularUi',
    parent: 'Angular'
  },
  {
    name: 'Angular',
    parent: 'Javascript'
  },
  {
    name: 'D3',
    parent: 'Javascript'
  }
];

var tree = [];

function getChilds(array,identifier){
    return _.filter(array,function(val){
        return val.parent == identifier
    });
}

function createTree(array){
    for(var x=0;x<_.size(array);x++){
      tree.push(array[x].name);
      var childs = getChilds(array,array[x].name);
        if(_.size(childs) > 0){
          createTree(childs);
        }else{
          $('div').append(JSON.stringify(tree));
        }
    }
}

createTree(categories);
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

预期产出

['Javascript','Jquery','Angular','AngularUi','D3']

这是我到目前为止所尝试的,并使用下划线提供一点帮助。任何帮助将不胜感激 。

1 个答案:

答案 0 :(得分:1)

我不知道你为什么要这样做(你所描述的结果根本就不是一棵树),但以下内容将提供你所描述的结果:

&#13;
&#13;
function addChildren(source, identifier, dest) {
  source.filter(function(val) {
    return val.parent == identifier;
  }).forEach(function(val) {
    dest.push(val.name);
    addChildren(source, val.name, dest);
  });
}

function buildTree(source) {
  var dest = [];
  addChildren(source, undefined, dest);
  return dest;
}

var categories = [{
  name: 'Javascript'
}, {
  name: 'jQuery',
  parent: 'Javascript'
}, {
  name: 'AngularUi',
  parent: 'Angular'
}, {
  name: 'Angular',
  parent: 'Javascript'
}, {
  name: 'D3',
  parent: 'Javascript'
}];


var tree = buildTree(categories);
&#13;
&#13;
&#13;

请注意,上面使用filter的方法是O(N 2 )操作(效率非常低)。

您可以先使用_.groupBy索引源arrray,将其更改为O(N)操作:

&#13;
&#13;
function addChildren(index, identifier, dest) {
    (index[identifier] || []).forEach(function (val) {
        dest.push(val.name);
        addChildren(index, val.name, dest);
    });
}

function buildTree(source) {
    var dest = [];
    addChildren(_.groupBy(source, 'parent'), undefined, dest);
    return dest;
}

var categories = [{
    name: 'Javascript'
}, {
    name: 'jQuery',
    parent: 'Javascript'
}, {
    name: 'AngularUi',
    parent: 'Angular'
}, {
    name: 'Angular',
    parent: 'Javascript'
}, {
    name: 'D3',
    parent: 'Javascript'
}];

var tree = buildTree(categories);
console.log(tree);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
&#13;
&#13;
&#13;