js 前端将平级数据转为树形数据的方法

时间:2020-07-27 17:41:08   收藏:0   阅读:158

转,实测成功

https://segmentfault.com/a/1190000022444269

    // 将同级数据转化为树形结构
    listToTree(dataSource) {
// datasource是平级的数据来源
      return dataSource.filter(e => {
        const pid = e.parentId
        const resultArr = dataSource.filter(ele => {
          if (ele.menuId === pid) {
            if (!ele.children) {
              ele.children = []
            }
            ele.children.push(e)
            return true
          }
        })
        return resultArr.length === 0
      })
    },

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!