溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在javascript中將list轉(zhuǎn)換成樹狀結(jié)構(gòu)

發(fā)布時間:2021-02-23 15:33:59 來源:億速云 閱讀:419 作者:戴恩恩 欄目:web開發(fā)

這篇文章主要為大家詳細介紹了如何在javascript中將list轉(zhuǎn)換成樹狀結(jié)構(gòu),文中示例代碼介紹的非常詳細,具有一定的參考價值,發(fā)現(xiàn)的小伙伴們可以參考一下:

JavaScript的特點

1.JavaScript主要用來向HTML頁面添加交互行為。 2.JavaScript可以直接嵌入到HTML頁面,但寫成單獨的js文件有利于結(jié)構(gòu)和行為的分離。 3.JavaScript具有跨平臺特性,在絕大多數(shù)瀏覽器的支持下,可以在多種平臺下運行。

如下所示:

/**
   * 將list裝換成tree
   * @param {Object} myId 數(shù)據(jù)主鍵id
   * @param {Object} pId  數(shù)據(jù)關(guān)聯(lián)的父級id
   * @param {Object} list list集合
   */
  function listToTree(myId,pId,list){
   function exists(list, parentId){
    for(var i=0; i<list.length; i++){
     if (list[i][myId] == parentId) return true;
    }
    return false;
   }
   
   var nodes = [];
   // get the top level nodes
   for(var i=0; i<list.length; i++){
    var row = list[i];
    if (!exists(list, row[pId])){
     nodes.push(row);
    }
   }
   
   var toDo = [];
   for(var i=0; i<nodes.length; i++){
    toDo.push(nodes[i]);
   }
   while(toDo.length){
    var node = toDo.shift(); // the parent node
    // get the children nodes
    for(var i=0; i<list.length; i++){
     var row = list[i];
     if (row[pId] == node[myId]){
      //var child = {id:row.id,text:row.name};
      if (node.children){
       node.children.push(row);
      } else {
       node.children = [row];
      }
      toDo.push(row);
     }
    }
   }
   return nodes;
  }
  
  var list=[
   {"ids":1,"parendId":0,"name":"Foods",url:"wwww"},
   {"ids":2,"parentId":1,"name":"Fruits"},
   {"ids":3,"parentId":1,"name":"Vegetables"},
   {"ids":4,"parentId":2,"name":"apple"},
   {"ids":5,"parentId":2,"name":"orange"},
   {"ids":6,"parentId":3,"name":"tomato"},
   {"ids":7,"parentId":3,"name":"carrot"},
   {"ids":8,"parentId":3,"name":"cabbage"},
   {"ids":9,"parentId":3,"name":"potato"},
   {"ids":10,"parentId":3,"name":"lettuce"},
   
   {"ids":11,"parendId":0,"name":"Foods"},
   {"ids":12,"parentId":11,"name":"Fruits"},
   {"ids":13,"parentId":11,"name":"Vegetables"},
   {"ids":14,"parentId":12,"name":"apple"},
   {"ids":15,"parentId":12,"name":"orange"},
   {"ids":16,"parentId":13,"name":"tomato"},
   {"ids":17,"parentId":13,"name":"carrot"},
   {"ids":18,"parentId":13,"name":"cabbage"},
   {"ids":19,"parentId":13,"name":"potato"},
   {"ids":20,"parentId":13,"name":"lettuce"}
  ];
  
  console.log(JSON.stringify(listToTree("ids","parentId",list)));
  console.log(listToTree("ids","parentId",list));

以上就是億速云小編為大家收集整理的如何在javascript中將list轉(zhuǎn)換成樹狀結(jié)構(gòu),如何覺得億速云網(wǎng)站的內(nèi)容還不錯,歡迎將億速云網(wǎng)站推薦給身邊好友。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI