美文网首页
JS实现树形与数组相互转换

JS实现树形与数组相互转换

作者: 莫问前程F6 | 来源:发表于2022-09-09 11:11 被阅读0次

    数据

    const arr =[
        {id:2,name:'部门B',parentId:0},
        {id:3,name:'部门C',parentId:1},
        {id:1,name:'部门A',parentId:2},
        {id:4,name:'部门D',parentId:1},
        {id:5,name:'部门E',parentId:2},
        {id:6,name:'部门F',parentId:3},
        {id:7,name:'部门G',parentId:2},
        {id:8,name:'部门H',parentId:4}
    ];
    

    数组转树形

    function toTree (data, pId) {
      const loop = parentId => {
        const res = []
        data.forEach(item => {
          if (item.parentId === parentId) {
            item.children = loop(item.id)
            res.push(item)
          }
        })
        return res
      }
      return loop(pId)
    }
    

    数组转树形

    function treeToArr(data) {
      const result = [];
      data.forEach(item => {
          const loop = data => {
              result.push({
                id: data.id,
                name: data.name,
                parentId: data.parentId
              });
              let child = data.children
              if(child){
                for(let i = 0; i < child.length; i++){
                  loop(child[i])
                }
              }
          }
          loop(item);
      })
      return result;
    }
    
    

    相关文章

      网友评论

          本文标题:JS实现树形与数组相互转换

          本文链接:https://www.haomeiwen.com/subject/pewanrtx.html