一個項目需求中,需要判斷數組中的對象是否有值,先看下數據結構:
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))