创建嵌套循环以在javascript中构建菜单

时间:2015-06-16 13:06:55

标签: javascript jquery arrays

这里我遇到了使用泛型函数创建嵌套循环并且对创建菜单有疑问的问题。

这里的行看起来像

id     data             parentId
1       HEADER1             0
2       HEADER2             0
3       HEADER3             0
4       HEADER4             0
5       H1SUB1              1
6       H1SUB1              1
7       H2SUB2              2
8       H2SUB2              2
9       H1SUB1sub1          5
10      H1SUB1sub1sub1      9

如何将其带到菜单

HEADER1                     HEADER2                         HEADER3                 HEADER4
    H1SUB1                      H2SUB2
    H1SUB1                      H2SUB2
        H1SUB1sub1
            H1SUB1sub1sub1

我试过的代码是

var arrObj = {};
for( var i=0;i<rows.length;i++){
    var row = rows[i],
    id=row.id,
    parentId = row.parentId;
    if(arrObj[parentId]){
      arrObj[parentId].items.push(row);
    } else if(parentId===0){
      arrObj[parentId] = {items=[]};    
  }
 }

这里我希望父ID 0只是页面中的HEADER。

帮我创建菜单,我应该如何获得它。提前致谢

1 个答案:

答案 0 :(得分:1)

创建一个你可能想要的解决方案,我不确定你想要的结果是什么,所以我假设结果是root是一个名为items的属性的对象,它是一个数组为了它的孩子。

var l = [
  {id: 1, data: 'HEADER1', parentId: 0},
  {id: 2, data: 'HEADER2', parentId: 0},
  {id: 3, data: 'HEADER3', parentId: 0},
  {id: 4, data: 'HEADER4', parentId: 0},
  {id: 5, data: 'H1SUB1', parentId: 1},
  {id: 6, data: 'H1SUB1',  parentId: 1},
  {id: 7, data: 'H2SUB2', parentId: 2},
  {id: 8, data: 'H2SUB2', parentId: 2},
  {id: 9, data: 'H1SUB1sub1', parentId: 5},
  {id: 10, data: 'H1SUB1sub1sub1', parentId: 9},
];

var getList = function(list) {


var result = {items: []},length = list.length;

   // Use object to create a hash of objects.
  var tmpStore = {}
  var i, item, id, pId;
  for (i = 0; i < length; ++i) {
    item = list[i];
    id = item.id;
    tmpStore[id] = item;
    pId = parseInt(item.parentId, 10);
    // If its pId is 0, then Added it to result's items, otherwise, find target
    // in list, and put to its item attribute(if no such attr, create it)
    if (pId === 0) {
      result.items.push(item);
    } else {
      if (typeof tmpStore[pId].items === 'undefined') {
        tmpStore[pId].items = [];
      }
      tmpStore[pId].items.push(item);
    }
  }

  return result;
};

编辑:更改为对象哈希映射。