国产探花免费观看_亚洲丰满少妇自慰呻吟_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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安国市| 江安县| 五大连池市| 米林县| 泰来县| 锦屏县| 涟源市| 罗定市| 成安县| 揭西县| 隆回县| 安吉县| 湘西| 丰原市| 江油市| 嘉峪关市| 湖南省| 甘洛县| 青阳县| 河间市| 卓资县| 徐汇区| 墨脱县| 闻喜县| 松滋市| 吕梁市| 盐源县| 定西市| 南岸区| 曲松县| 香河县| 乌兰察布市| 新建县| 吴桥县| 寿光市| 苏尼特右旗| 大竹县| 聂荣县| 浮梁县| 东台市| 齐齐哈尔市|