我有一个可以尽可能深嵌套的对象。我试图确定对象的属性ready
是否至少有一个假值。如果是这样,checkForFalse
函数应该返回false。我在使用递归来解决这个问题时感到困惑。应该返回什么递归调用以使此代码有效?或者我完全错了,错过了什么?
var obj = {
"currentServiceContractId": {
"ready": true,
"customerPersonId": {
"ready": false
}
},
"siteId": {
"ready": true
},
"districtId": {},
"localityId": {
"ready": true
},
"streetId": {
"ready": true
}
};
function checkForFalse(mainObj) {
let ans = _.find(mainObj || obj, (val) => {
if (_.keys(val).length > 1) {
let readyObj = _.pick(val, 'ready');
return checkForFalse(readyObj);
} else {
return _.get(val, 'ready') === false;
}
});
return _.isEmpty(ans);
}
console.log(checkForFalse(obj));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
答案 0 :(得分:0)
此解决方案递归使用_.every()
来搜索ready: false
。当回调返回_.every()
时,false
方法将立即返回:
function checkForAllReady(mainObj) {
return _.every(mainObj, (value, key) => {
if(key === 'ready' && value === false) {
return false;
}
if(_.isObject(value)) {
return checkForAllReady(value);
}
return true;
});
}
const obj = {"currentServiceContractId":{"ready":true,"customerPersonId":{"ready":true}},"siteId":{"ready":true},"districtId":{},"localityId":{"ready":true},"streetId":{"ready":true}};
console.log(checkForAllReady(obj));
const objWithFalse = _.merge({}, obj, { "streetId":{"ready":false} })
console.log(checkForAllReady(objWithFalse));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;