玉循环通过对象并将子项分配给父母

时间:2014-08-08 11:02:11

标签: javascript node.js express pug

我有一个名为“board”的对象。

[{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912"},
{"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"},
{"id":3,"parent_board":1,"title":"Lorem 1-1","description":"6062bc28a9f781e06417d"}]

现在我想在Jade中遍历这个对象。

这是我目前的javascript函数:

var htmlElem = document.getElementById('htmlElemId');
htmlElem.innerHTML = "";

for(var i = 0; i < boards.length; i++){
  if(boards[i].parent_board == 0){
    htmlElem.innerHTML += "<li id='" + boards[i].id + "'>" + boards[i].title + "</li>";
  }else{
    var parent = document.getElementById(boards[i].parent_board);
    if (parent){
      parent.innerHTML += "<ul><li id='" + boards[i].id + "'>" + boards[i].title + "</li></ul>";
    }
  }
}

如您所见,具有“parent_board”值的所有电路板都会自动分配给其父板。

所以使用这个Javascript函数我的结果如下:

  • Lorem 1
    • Lorem 1-1
  • Lorem 2

没关系。

但是我试图在pure Jade中存档,但没有运气。这是我的玉代码:

each board in boards
  if board.parent_board
    ul
      li = #{board.title}
  else
    li = #{board.title}

结果如下:

  • Lorem 1
  • Lorem 2
    • Lorem 1-1

我的Jade代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

问题是,在javascript代码中,您将第二个列表附加到正确的父元素。在您拥有的玉代码中,您只是将其附加到html的末尾,因此它将始终以该特定顺序显示。简单的解决方案是将Lorem1对象放在Lorem1之后的数组中,但效率非常低。

模板引擎实际上只适用于非常轻的逻辑,我们正在进入复杂逻辑的领域,而不会稍微改变数据结构。将您的板对象更改为两个单独的对象可能更好:

boards = [{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912"},
         {"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"}];

subboards = [{"id":3,"parent_board":1,"title":"Lorem 1-1","description":"6062bc28a9f781e06417d"}];

这样你的玉器代码可以改为:

each board in boards
  li = #{board.title}
  each subboard in subboards
    if subboard.parent_board == board.id
      ul
        li = #{subboard.title} 

或者,更好的解决方案是更改板对象,以便子板位于父板内:

boards = [{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912", "subboards": 
             [{"id":3,"parent_board":1,"title":"Lorem 1-1","description":"6062bc28a9f781e06417d"}]},
         {"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"}];

each board in boards
  li = #{board.title}
  each subboard in board.subboards
      ul
        li = #{subboard.title} 

JS用于从平面数据结构填充对象。请注意,在jade模板中,您应该更改它,以便它只插入具有parent_board == 0的板或从主数组中删除子板对象:

for(var i = 0; i < boards.length; i++){

  var boardId = boards[i].id;
  var boardParent = boards[i].parent_board;

  if(boardParent !== 0){
    // Check to see if the array exists for a start
    if (!boards[boardParent].subboards) {
        // If not then create a new array
        boards[boardParent].subboards = [];
    }
    boards[boardParent].subboards.push(boards[i]);
  }
}