簡體   English   中英

使用 Javascript 遞歸檢查 object 中的任何 null/未定義鍵/值

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

我有輸入

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

等等。 它評估為

(false || true || (true && true))這是真的

我需要檢查輸入是否有任何鍵/值,即 null / undefined / numeric key / not in above format

鍵可以是'OR' 'AND',數組值只需為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]);
                    }
                });
            };

有沒有更優雅的方法來做到這一點?

您可以檢查類型並使用迭代和遞歸方法

 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' }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM