js將樹形結構的數組扁平化(按順序)


    treeData(arr) {
        let cloneData = JSON.parse(JSON.stringify(arr))   //先將原來的數組深拷貝一份,防止影響到原來的數據
        return cloneData.filter(father => {
            let branchArr = cloneData.filter(child => father.id == child.parentId);
            branchArr.length > 0 ? father.children = branchArr : ''
            return father.parentId == null    //返回第一層的數據,如果最上一級的父級id不是null,請自行修改
        })
    }
 
調用 this.treeData(json數組)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM