JavaScript集合(Array)转树(tree)结构

js 原生数组转树形结构
 
/**

 * 将list装换成tree
 * @param {Object} myId 数据主键id
 * @param {Object} pId  数据关联的父级id
 * @param {Object} children 子节点的节点名称
 * @param {Object} paramList list数据集合
 */
function listToTree(myId, pId,children, paramList) {
  function recursion(id,pId,all,item){
    let childrenList=all.filter(ele=>ele[pId] === item[id]);
    if (childrenList&&childrenList.length>0){
      childrenList.forEach(function(f){
        recursion(id,pId,all,f);
      })
      let myChildrenList = item[children];
      if (myChildrenList === undefined){
          myChildrenList=[];
      }
      childrenList.forEach(o=>myChildrenList.push(o));
      item[children]=myChildrenList;
    }
  }

  if (!paramList||paramList.length===0){
    return [];
  }
  let list = JSON.parse(JSON.stringify(paramList));
  let parentList=list.filter(ele=>ele[pId] === null||ele[pId] === undefined);
  if (!parentList){
    return [];
  }
  parentList.forEach(function(it){
    recursion(myId,pId,list,it);
  })
  return  parentList;
}

调用:
	function dealData(){
		let treeData=listToTree('id','pid','subList',listData);
		console.log(treeData);
	}

执行结果:
执行结果

评论区域

评论功能已关闭. 提示:评论功能虽已关闭,关闭之前的评论仍然会展示。