二维数组转树结构

需求: 将级联多选框选择后得到的二维数组重新组成一个新的级联多选框, 级联多选框选择后得到的是一个二维数组, 需要转成树结构.

例如:

let arr = [
  [100, 110, 111],
  [100, 120, 129],
  [100, 120, 169],
  [500, 520, 521, 521.2],
  [500, 550, 522]
]

前提: 二维数组的每一项第一个必须是顶节点,  后面每一个都是前一个的子节点, 例如[100,110,111] 中, 100是顶节点, 110的父节点是100, 111的父节点是110.

 方法

function toTree(arr) {
  let tree = []
  arr.forEach((list) => {
    search(list, tree)
  })
  return tree

  function search(list, tree) {
    if (list.length) {
      //判断tree中是否有list[0], 有则返回下标, 没有则返回-1
      let index = getIndex(list[0], tree)
      if (index !== -1) {
        //已有该节点,继续向下找
        search(list.slice(1), tree[index].childList)
      } else {
        //没有该节点创建节点
        tree.push(format(list))
      }
    }
  }
  function format(list) {
    return list.length
      ? {
          id: list[0],
          childList: [format(list.slice(1))]
        }
      : []
  }
  function getIndex(id, list) {
    for (let i in list) {
      if (list[i].id === id) {
        return i
      }
    }
    return -1
  }
}

结果: 

toTree(arr)

// [
//   ({
//     id: 100,
//     childList: [
//       {
//         id: 110,
//         childList: [{ id: 111, childList: [] }]
//       },
//       {
//         id: 120,
//         childList: [
//           { id: 129, childList: [] },
//           { id: 169, childList: [] }
//         ]
//       }
//     ]
//   },
//   {
//     id: 500,
//     childList: [
//       {
//         id: 520,
//         childList: [
//           {
//             id: 521,
//             childList: [{ id: 521.2, childList: [] }]
//           }
//         ]
//       },
//       {
//         id: 550,
//         childList: [{ id: 522, childList: [] }]
//       }
//     ]
//   })
// ]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值