数组扁平化-多维数组转化为一维数组

代码
/**
  arr: 需要进行扁平化的数组;
  returnArr: 返回值(因需要多次遍历到同一数组中)
  isChildren: 扁平化后子元素是否还包含在当前元素中;
  id: 在子元素中添加识别父元素的唯一标识;
  pid: 标识在父元素中的属性名;
  branch: 需要扁平的子元素;
*/
flatteningData(arr, returnArr, isChildren=false, id='pid', pid='id', branch='children'){
   let list = returnArr , data = {}
   arr = JSON.parse(JSON.stringify(arr))
   while(data = arr.shift()){
     const {[branch]:children, ...item} = data
     list.push(isChildren ? data : item) 
     if(children && children.length){
        this.flatteningData(children, list,  isChildren, id, pid, branch)
      }
    }
    return list
}
案例
test(){
  const arr = [
    {
      text:'吃食',
      id:1,
      children:[
        {
          text:'水果',
          id:11,
          children:[
            {
              text:'苹果',
              id:111
            },
            {
              text:'葡萄',
              id:112
            },
            {
              text:'梨子',
              id:113
            }
          ]
        },
        {
          text:'零食',
          id:12,
          children:[
            {
              text:'锅巴',
              id:121
            },
            {
              text:'辣条',
              id:122
            }
          ]
        },
        {
          test:'肉类',
          id:13,
          children:[
            {
              text:'鸭肉',
              id:131
            },
            {
              text:'鸡肉',
              id:132
            }
          ]
        }
      ]
    }
  ]
  console.log('结果111', this.flatteningData(arr, []))
}
// 结果
[
    {
        "text": "吃食",
        "id": 1
    },
    {
        "text": "水果",
        "id": 11
    },
    {
        "text": "苹果",
        "id": 111
    },
    {
        "text": "葡萄",
        "id": 112
    },
    {
        "text": "梨子",
        "id": 113
    },
    {
        "text": "零食",
        "id": 12
    },
    {
        "text": "锅巴",
        "id": 121
    },
    {
        "text": "辣条",
        "id": 122
    },
    {
        "test": "肉类",
        "id": 13
    },
    {
        "text": "鸭肉",
        "id": 131
    },
    {
        "text": "鸡肉",
        "id": 132
    }
]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值