检查对象属性时递归混乱
Recursion mess while checking object properties
我有一个可以尽可能深地嵌套的对象。我正在尝试确定对象的 属性 ready
是否至少有一个错误值。如果是这样,checkForFalse
函数应该 return 为假。我在使用递归解决这个问题时感到困惑。 return 应该进行什么递归调用才能使此代码正常工作?或者我完全错了,遗漏了什么?
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>
此解决方案使用 _.every()
递归搜索 ready: false
。当回调 returns false
:
时,_.every()
方法将立即 return
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));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
我有一个可以尽可能深地嵌套的对象。我正在尝试确定对象的 属性 ready
是否至少有一个错误值。如果是这样,checkForFalse
函数应该 return 为假。我在使用递归解决这个问题时感到困惑。 return 应该进行什么递归调用才能使此代码正常工作?或者我完全错了,遗漏了什么?
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>
此解决方案使用 _.every()
递归搜索 ready: false
。当回调 returns false
:
_.every()
方法将立即 return
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));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>