js数组、json数据扁平化

js数组扁平化

// 原始数据
let arr = [1,2,[3,4,[5,6,[7,8,[9,10],11],12],13],14,[15,[16,[17,18]]]];
代码如下:
let dofn = (arr) =>{
    let result = [];
    let tempArr = (params) =>{
        params.forEach(element => {
            if(Array.isArray(element)){
                // 递归: 函数自己调用自己。
                tempArr(element);
            }else{
                result.push(element);
            }
        });
    }
    tempArr(arr);
    return result;
}
console.log('新数组--', dofn(arr));
// 打印结果:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

json数据扁平化

// 原始数据
let obj = {
    id: 1,
    age: 11,
    children: [
        {
             id: 2,
             age: 22,
             children: [
                 {
                      id: 7,
                      age: 77,
                      children: [],
                 }
             ]
         },
         {
             id: 3,
             age: 33,
             children: [
                 {
                     id: 4,
                     age: 44,
                 },
                 {
                     id: 5,
                     age: 55,
                     children: [
                         {
                             id: 6,
                             age: 66,
                             children: []
                         }
                     ]
                 }
             ]
         },
         {
             id: 8,
             age: 88,
             children: [
                 {
                     id: 9,
                     age: 99,
                     children: [],
                 }
             ]
         },
         {
             id: 10,
             age: 100,
             children: [],
         }
     ]
}
代码如下:
let objFn = (params) =>{
    let arr = [];
    arr.push(params);
    let result = [];
    let changeFn = (a, parentId = null) =>{
        a.forEach((item)=>{
        //ES6:解构运算符...为剩余运算符,是扩展运算符的一种用法。
        let { children, ...i } = item;
            result.push({
                ...i,
                parentId,
            });
            if(children && children.length){
                // 递归。          传入父id
                changeFn(children, item.id);
            }
        })
    }
    changeFn(arr);
    return result;
}
console.log('json--', objFn(obj));

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

&做梦的少年&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值