Recursively check for any null / undefined keys / values in an object using Javascript

810 Views Asked by At

I have input like

{'OR': [false, true, {'AND': [true, true]}]}

and so on. It evaluates to

(false || true || (true && true)) which is true

I need to check if input has any key / value which is null / undefined / numeric key / not in above format

keys can be 'OR' 'AND', Array values only need to be boolean

var isValid = true;
var checkArr = function(obj){
                if(obj === null){
                    isValid = false;
                    return;
                }
                if(Array.isArray(obj)){
                    obj.forEach(function(k){
                        if(!(typeof(k) === 'boolean' || typeof(k) === 'object' && (k !== null && k !== undefined))){
                            isValid = false;
                            return;
                        }
                    });
                }
                else if(typeof(obj) === 'object'){
                    var key = Object.keys(obj)[0];
                    if(['OR', 'AND'].indexOf(key) === -1){
                        isValid = false;
                        return;
                    }
                }
                Object.keys(obj).forEach(function(key){
                    if(typeof(obj[key]) === 'object'){
                        checkArr(obj[key]);
                    }
                });
            };

Is there a more elegant way to do this?

1

There are 1 best solutions below

2
On

You could check the types and use an iterative and recursive approach

const
    check = object => Object.keys(object).length === 1 
       && ('AND' in object !== 'OR' in object)
       && Array.isArray(object.AND || object.OR)
       && (object.AND || object.OR).length !== 0
       && (object.AND || object.OR).every(v =>
           typeof v === 'boolean' ||
           v && typeof v === 'object' && check(v)
       );


console.log(check({ OR: [false, true, { AND: [true, true] }] }));
console.log(check({ OR: [false, true, { AND: [true, 1] }] }));
console.log(check({ AND: 'foo', OR: [false, true, { AND: [true, true] }] }));
console.log(check({ OR: [] }));
console.log(check({ OR: [], a: 'test' }));
console.log(check({ a: 'test' }));