前端 js data数组转tree数据结构

思路

1、首先数据是Excel表格,无pId,但是需要按照目录层级顺序排好(并且是按照到每一层级的最里层);前端根据目录层级,进行pId的赋值及取值;

2、为每一条数据添加pId:

  1. 观察表格数据结构,是否为叶子节点与其他字段无关,只与上一层级的zIndex大小有关;
  2. 当前项zIndex与前一项的zIndex的大小关系:
    此处zIndex 默认从1开始,是顶层
  • current > before:说明是前一项的子节点,当前项的pId即为前一项的id
  • current === before: 说明他们有相同父节点是兄弟关系,current.pId = before.pId
  • current < before: 说明有多个平级节点,需要往前推,找到最近的兄弟节点,即直接取其pId即可,current.pId = data[n].pId
    此处使用一个for循环,根据当前index,往前递减,找到立即break跳出循环,即可
// 根据zIndex:添加 pId 
                    if(item.zIndex === 1){
                        item.pId = null;
                    }else{
                        flag = index;
                        let beforeItem = _data[index - 1];
                        if(beforeItem.zIndex < item.zIndex){
                            item.pId = beforeItem.id
                        }else if(beforeItem.zIndex === item.zIndex) {
                            // 相等的情况
                            item.pId = beforeItem.pId; // 与之前项的pId值同
                        }else{
                            // 当前pId < 前一项的 pId
                            for(let n = index; n--; n > flag){
                                if(_data[n].zIndex === item.zIndex){
                                    console.log("当 前一项时 > 当前zIndex ",beforeItem.name,beforeItem.zIndex,item.name,item.zIndex);
                                    console.log(n,_data[n].name,"flag标识--",flag);
                                    item.pId = _data[n].pId; // 向上找 找到 同层级 取其pId
                                    break; // 遇到立即跳出循环
                                }
                            }
                        }
                    }

难点:根据pId进行树的数据转换

参考示例:https://www.cnblogs.com/wjs0509/p/11082850.html

/**
 * 该方法用于将有父子关系的数组转换成树形结构的数组
 * 接收一个具有父子关系的数组作为参数
 * 返回一个树形结构的数组
 */
function translateDataToTree(data) {
  //没有父节点的数据
  let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null)
 
  //有父节点的数据
  let children = data.filter(value => value.parentId !== 'undefined' && value.parentId != null)
 
  //定义转换方法的具体实现
  let translator = (parents, children) => {
    //遍历父节点数据
    parents.forEach((parent) => {
      //遍历子节点数据
      children.forEach((current, index) => {
        //此时找到父节点对应的一个子节点
        if (current.parentId === parent.id) {
          //对子节点数据进行深复制,这里只支持部分类型的数据深复制,对深复制不了解的童靴可以先去了解下深复制
          let temp = JSON.parse(JSON.stringify(children))
          //让当前子节点从temp中移除,temp作为新的子节点数据,这里是为了让递归时,子节点的遍历次数更少,如果父子关系的层级越多,越有利
          temp.splice(index, 1)
          //让当前子节点作为唯一的父节点,去递归查找其对应的子节点
          translator([current], temp)
          //把找到子节点放入父节点的children属性中
          typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
        }
      }
      )
    }
    )
  }
 
  //调用转换方法
  translator(parents, children)
 
  //返回最终的结果
  return parents
}
原文地址:https://www.cnblogs.com/hqq422/p/14984903.html