删除树结构中的空数组

遍历删除数组中所有元素为 dept 是1 且没有children 字段的 或者 children 为空的元素

调用

    this.parent_data = tree;
    this.removeEmptyChildren(tree);

如果删除的元素是当前遍历的元素,需要向前移动一位,否则会跳过该元素

递归遍历删除方法

    removeEmptyChildren(data) {
                for (let i = data.length - 1; i >= 0; i--) {
                    const item = data[i];
                    if (item.children) {
                        this.removeEmptyChildren(item.children);
                        if (item.dept === "1" && item.children.length === 0) {
                            console.log(data[i].label);
                            data.splice(i, 1);
                        }
                    } else if (item.dept === "1") {
                        console.log(data[i].label);
                        data.splice(i, 1);
                    }
                }
            },

原数据树

[{
    "account": "",
    "children": [{
        "account": "",
        "dept": "1",
        "id": "122049393-0101",
        "label": "智联",
        "phone": "",
        "pid": "122049393-01",
        "sex": ""
    }, {
        "account": "",
        "children": [{
            "account": "",
            "dept": "1",
            "id": "122049393-010201",
            "label": "摄像机海淀区海康233",
            "phone": "",
            "pid": "122049393-0102",
            "sex": ""
        }, {
            "account": "",
            "children": [{
                "account": "",
                "dept": "1",
                "id": "122049393-01020201",
                "label": "哈哈哈哈",
                "phone": "",
                "pid": "122049393-010202",
                "sex": ""
            }],
            "dept": "1",
            "id": "122049393-010202",
            "label": "摄像机海淀区大华243",
            "phone": "",
            "pid": "122049393-0102",
            "sex": ""
        }],
        "dept": "1",
        "id": "122049393-0102",
        "label": "摄像机北京市组织",
        "phone": "",
        "pid": "122049393-01",
        "sex": ""
    }, {
        "account": "",
        "children": [{
            "account": "",
            "dept": "1",
            "id": "122049393-010301",
            "label": "哈哈",
            "phone": "",
            "pid": "122049393-0103",
            "sex": ""
        }],
        "dept": "1",
        "id": "122049393-0103",
        "label": "摄像机河南",
        "phone": "",
        "pid": "122049393-01",
        "sex": ""
    }],
    "dept": "1",
    "id": "122049393-01",
    "label": "智联总部演示",
    "phone": "",
    "pid": "000000",
    "sex": ""
}]
JS:遍历删除上面数组中所有元素为 dept 是1 且没有children 字段的 或者 children 为空的元素
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容