js 树形json转以叶子结点为基准的扁平结构

需求,我需要根据树形结构,来实现自定义表格,所以需要转化,下面是代码:

const shortid = require('shortid')

const data = [
  {
    name: 'a',
    children: [
      {
        name: 'b',
        children: [{ name: 'e' }, { name: 'i' }],
      },
      { name: 'c', children: [{ name: 'f' }] },
      { name: 'd', children: [{ name: 'g' }] },
    ],
  },
  {
    name: 'a2',
    children: [
      { name: 'b2', children: [{ name: 'e2' }] },
      { name: 'c2', children: [{ name: 'f2' }] },
      { name: 'd2', children: [{ name: 'g2' }] },
    ],
  },
]

// 深度遍历, 使用递归
function getName(data) {
  const resultArr = []
  data.forEach(item => {
    const itemArr = []
    const map = (node, level, parent) => {
      if (!node.id) {
        node.id = shortid.generate()
      }
      if (parent == null) {
        resultArr.push({
          key: node.id,
          arr: [node.name],
        })
      }
      itemArr.push(`${node.name}-${level}`)
      if (node.children) {
        const parentIndex = resultArr.findIndex(x => {
          return x.key == node.id
        })
        // 截取前面公用部分
        const commonArr = resultArr[parentIndex].arr.slice(0, level)
        const replaceArr = []
        node.children.forEach((child, index) => {
          child.id = shortid.generate()
          replaceArr.push({
            key: child.id,
            arr: commonArr.concat(child.name),
          })
        })
        resultArr.splice(parentIndex, 1, ...replaceArr)
        node.children.forEach(child => {
          map(child, level + 1, node)
        })
      }
    }
    map(item, 1, null)
  })

  return resultArr
}

const tableData = getName(data)
console.log(tableData)

输出结果:

[
  { key: 'Ij4KszNXGh', arr: [ 'a', 'b', 'e' ] },
  { key: '_YmL4zRB51', arr: [ 'a', 'b', 'i' ] },
  { key: 'Hy1PxIkC3z', arr: [ 'a', 'c', 'f' ] },
  { key: 'znTOT_qr_F', arr: [ 'a', 'd', 'g' ] },
  { key: 'J5h4SrVgXz', arr: [ 'a2', 'b2', 'e2' ] },
  { key: '-2zaoRtf1O', arr: [ 'a2', 'c2', 'f2' ] },
  { key: 'NZ66jv8bMI', arr: [ 'a2', 'd2', 'g2' ] }
]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值