How to check if object within object exists

后端 未结 6 817
慢半拍i
慢半拍i 2021-01-12 08:21

It seems that the following technique for checking the existence of an object member produces an error because the \'bar\' parent object hasn\'t been declared before the che

6条回答
  •  死守一世寂寞
    2021-01-12 08:43

    As Matthew Abbott gave in his response, you can write a method for it to use it later if you do a lot of diving into child properties where the whole object or somewhere along the chain can be null. Below is my implementation using lodash.

    checkGraph(obj, graphPath) {
        if (obj) {
          let root = obj;
          _.each(graphPath.split('.'), part => {
            if (root[part]) {
              root = root[part];
            } else {
              return false; // bad property
            }
          });
          return true;
        }
        return false; // bad object
      }
    

    You can call the method like this:

    if (this.checkGraph(object, 'property.subproperty') {
        // do thing
    }
    

提交回复
热议问题