0

I have an object which could be nested as deep as possible. I'm trying to determine if object's property ready has at least one false value. If so the checkForFalse function should return false. I got confused while using recursion to solve this problem. What recursion call should return to make this code work? Or I'm completely wrong and missing something?

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>
tawreon
  • 184
  • 12
  • What specifically is the problem? What's the output vs what you expect? – Carcigenicate Oct 18 '17 at 21:33
  • I expect to have console.log to output `false` if any of object property named `ready` has `false` value. Now I'm always getting `false` console logged – tawreon Oct 18 '17 at 21:37
  • 1
    Just an observation. You have a function named `checkForFalse` that you want to return `false` if there is a false. To me that's a very misleading function name,. Without knowing what the function did, I would expect by it's name that `checkForFalse` would return `true` if a found a `false`. – Keith Oct 18 '17 at 22:04
  • 1
    @Keith is right. Something like `checkForAllReady` would better reflect the idea behind the method. – Ori Drori Oct 18 '17 at 22:16

1 Answers1

0

This solution uses _.every() recursively to search for ready: false. The _.every() method will return immediately when the callback returns 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));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209