0
点赞
收藏
分享

微信扫一扫

JavaScript数组转树

诗与泡面 2022-03-31 阅读 83
javascript
function arrayToTree(array) {
  const root = array[0]
  array.shift()
  const tree = {
    id: root.id,
    val: root.val,
    children: array.length > 0 ? toTree(root.id, array) : []
  }
  return tree
}

function toTree(parenId, array) {
  const children = []
  const len = array.length
  for (let i = 0; i < len; i++) {
    const node = array[i]
    if (node.parentId === parenId) {
      children.push({
        id: node.id,
        val: node.val,
        children: toTree(node.id, array)
      })
    }
  }
  return children
}
举报

相关推荐

0 条评论