递归过滤数组对象

134 阅读1分钟

个人记录

//数据
const arr = [
    {
        id:1,
        has: true,
        child:[
            {
                id:'1-1',
                has:true,
                child:[
                    {
                        id:'1-1-1',
                        has: true
                    }
                ]
            }
        ]
    },
    {
        id:2,
        has: true,
        child:[
            {
                id:'2-1',
                has:true,
                child:[
                    {
                        id:'2-1-1',
                        has: false
                    }
                ]
            }
        ]
    },
    {
        id:3,
        has: false,
        child:[
           
        ]
    },
    {
        id:4,
        has: false,
        child:[
           
        ]
    },
    {
        id:5,
        has: true,
        child:[
           
        ]
    }
]


function filterTrue(data){
    const res = []
    data.forEach(item =>{
    const tmp = {...item}
        if(tmp.has){
            if(tmp.child){
              tmp.child = filterTrue(tmp.child)
            }
            res.push(tmp)
        }
    })
    return res
}

filterTrue(arr)

//打印
[
    {
        "id": 1,
        "has": true,
        "child": [
            {
                "id": "1-1",
                "has": true,
                "child": [
                    {
                        "id": "1-1-1",
                        "has": true
                    }
                ]
            }
        ]
    },
    {
        "id": 2,
        "has": true,
        "child": [
            {
                "id": "2-1",
                "has": true,
                "child": []
            }
        ]
    },
    {
        "id": 5,
        "has": true,
        "child": []
    }
]