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数组)
posted @ 2020-06-28 17:05  我是一只小码农  阅读(3472)  评论(0编辑  收藏  举报