JS는 목록을 트리 구조로 변환합니다.

php中世界最好的语言
풀어 주다: 2018-04-18 11:39:19
원래의
3474명이 탐색했습니다.

이번에는 목록을 트리 구조로 변환하는 JS를 가져오겠습니다. JS가 목록을 트리 구조로 변환하는 데 필요한 notes는 무엇인가요?

/**
   * 将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));
로그인 후 복사

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

추천 도서:



위 내용은 JS는 목록을 트리 구조로 변환합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!