js数据结构处理—树状结构数组扁平化

之前朋友问过我一个问题,项目中遇到树状结构的数组不知如何扁平化,下面贴一下问题和解决方案:

以下是需要做处理的数据:

var arr = [
  {
    id: 1,
    name: 'a',
    child: [
      {
        id: 2,
        name: 'b',
        child: [
          {
            id: 3,
            name: 'c',
            child: [],
          },
        ],
      },
    ],
  },
  {
    id: 4,
    name: 'd',
    child: [
      {
        id: 5,
        name: 'e',
        child: [
          {
            id: 6,
            name: 'f',
            child: [],
          },
        ],
      },
    ],
  },
]

需求是需要把每一级的child中的内容拉到第一级中,并去掉child属性,拿到问题无非就是只要有child层级,就拿它的属性过来,填充到新数组中,无限递归下去。

下面是解决方案:

// 方法一
function flag(arr) {
  let result = []
  for (item of arr) {
    var res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据作为第一层级的填充
    delete res['child']
    result.push(res)
    if (item.child instanceof Array && item.child.length > 0) { // 如果当前child为数组并且长度大于0,才可进入flag()方法
      result = result.concat(flag(item.child))
    }
  }
  return result
}
console.log(flag(arr))
// 方法二
var array = []
function getData(arr, type = 'child') {
  arr.forEach((res) => {
    var resType = JSON.parse(JSON.stringify(res)) // 先克隆一份数据作为第一层级的填充
    delete resType[type]
    array.push(resType)
    if (Array.isArray(res[type]) && res[type].length > 0) { // 如果当前child为数组并且长度大于0,才可进入flag()方法
      getData(res[type])
    }
  })
  return array
}
console.log(getData(arr))

其实两种方法逻辑相同,只是细节上的写法有出入,看个人习惯,并且新数组的作用域不同,所以方法一才需要concat()。

两种方法输出结果一致。

输出结果:

[ { id: 1, name: 'a' },
  { id: 2, name: 'b' },
  { id: 3, name: 'c' },
  { id: 4, name: 'd' },
  { id: 5, name: 'e' },
  { id: 6, name: 'f' } ]
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值