Bootstrap

递归判断多维数组中对象是否有值

一个项目需求中,需要判断数组中的对象是否有值,先看下数据结构:

let list = [
        {
            value: "1",
            children: [
                {
                    value: "2",
                },
                {
                    value: "3",
                    children: [
                        {
                            value: "4",
                        },
                    ]
                }
            ]
        },
        {
            value: "5",
        }
    ]

那么如何进行判断多层子集是否有值呢?这里就会用到递归来实现

    function ruleValidate(data) {
        let flag = true;
        var arr = [];
        function judgeChildren(data) {
            data.forEach(e => {
                if (!flag) {
                    return
                }
                if (!e.value) {
                    flag = false;
                    return;
                } else if (e.children && e.children.length) {
                    judgeChildren(e.children);
                }
            });
        }
        judgeChildren(data);
        return flag;
    }
    console.log(ruleValidate(list))

 

转载于:https://www.cnblogs.com/yuzhongyu/p/10976283.html

;