国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

javascript將list轉換成樹狀結構的實例

2024-05-06 16:39:34
字體:
來源:轉載
供稿:網友

如下所示:

/**   * 將list裝換成tree   * @param {Object} myId 數據主鍵id   * @param {Object} pId  數據關聯的父級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轉換成樹狀結構的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长沙市| 峨山| 肇源县| 五大连池市| 武威市| 卓尼县| 博爱县| 阿荣旗| 万盛区| 邵东县| 金平| 逊克县| 广河县| 榆林市| 兰考县| 称多县| 安宁市| 黑水县| 嘉禾县| 临颍县| 宣恩县| 临沂市| 宁化县| 金塔县| 四子王旗| 盐池县| 汨罗市| 美姑县| 会东县| 康乐县| 都匀市| 琼海市| 加查县| 鄯善县| 尖扎县| 边坝县| 河南省| 中超| 中牟县| 昌都县| 托克逊县|