Object has-property-deep check in JavaScript

后端 未结 8 2046
走了就别回头了
走了就别回头了 2020-12-01 21:16

Let\'s say we have this JavaScript object:

var object = {
   innerObject:{
       deepObject:{
           value:\'Here am I\'
       }
   }
};
<
8条回答
  •  北海茫月
    2020-12-01 21:49

    My approach would be using try/catch blocks. Because I don't like to pass deep property paths in strings. I'm a lazy guy who likes autocompletion :)

    JavaScript objects are evaluated on runtime. So if you return your object statement in a callback function, that statement is not going to be evaluated until callback function is invoked.

    So this function just wraps the callback function inside a try catch statement. If it catches the exception returns false.

    var obj = {
      innerObject: {
        deepObject: {
          value: 'Here am I'
        }
      }
    };
    
    const validate = (cb) => {
      try {
        return cb();
      } catch (e) {
        return false;
      }
    }
    
    
    if (validate(() => obj.innerObject.deepObject.value)) {
     // Is going to work
    }
    
    
    if (validate(() => obj.x.y.z)) {
     // Is not going to work
    }

    When it comes to performance, it's hard to say which approach is better. On my tests if the object properties exist and the statement is successful I noticed using try/catch can be 2x 3x times faster than splitting string to keys and checking if keys exist in the object.

    But if the property doesn't exist at some point, prototype approach returns the result almost 7x times faster.

    See the test yourself: https://jsfiddle.net/yatki/382qoy13/2/

    You can also check the library I wrote here: https://github.com/yatki/try-to-validate

提交回复
热议问题