(js)扁平数组树状化 树状数组扁平化

 扁平数组树状化(利用递归,两个函数完成树状转化 )

数组格式: 

let list = [
  { id: 1, title: '标题1', p_id: 0 },
  { id: 2, title: '标题2', p_id: 0 },
  { id: 3, title: '标题2-1', p_id: 2 },
  { id: 4, title: '标题2-2', p_id: 2 },
  { id: 5, title: '标题2-2-1', p_id: 4 },
  { id: 6, title: '标题2-2-1-1', p_id: 5 },
  { id: 7, title: '标题2-2-1-2', p_id: 5 },
]
function getTree (arr) {
  const treeData = []
  arr.forEach(v => {
    //找到第一层父节点
    if (v.p_id === 0) {
      treeData.push(v)
      v.children = getChildren(arr, v.id)
    }
  })
  return treeData
}
function getChildren (arr, id) {
  const children = []
  //查找父节点对应的子节点
  arr.forEach(v => {
    if (v.p_id === id) {
      v.children = getChildren(arr, v.id)
      children.push(v)
    }
  })
  return children
}
console.log(getTree(list))//打印输出结果

树状数组扁平化

直接利用上面转化结果进行扁平化

//树状扁平化
function flatten (data) {
  return data.reduce((pre, cur) => {
    const { id, title, p_id, children = [] } = cur
    return pre.concat([{ id, title, p_id }], flatten(children))
  }, [])
}
console.log(flatten(fu(list)))

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值