Check if object member exists in nested object

后端 未结 8 936
花落未央
花落未央 2020-11-27 05:00

Is there a simpler way than using ___ in object to check the existence of each level of an object to check the existence of a single member?

More conci

相关标签:
8条回答
  • 2020-11-27 05:20

    Something like (warning: untested code ahead)

    var testProperty = function(obj, proplist) {
       for (var i=0; i < proplist.length; i++) {
          if (obj.hasOwnProperty(proplist[i])) {
             obj = obj[proplist[i]];
          } else {
            return false;
          }
       }
       return true;
    }
    
    0 讨论(0)
  • 2020-11-27 05:22

    Here's one way: http://jsfiddle.net/9McHq/

    var result = ((((someObject || {}).member || {}).member || {}).member || {}).value;
    
    alert( result );
    
    0 讨论(0)
  • 2020-11-27 05:26

    You could also try/catch TypeError?

    try {
      console.log(someObject.member.member.member.value);
    } catch(e) {
      if (e instanceof TypeError) {
        console.log("Couldn't access someObject.member.member.member.value");
        console.log(someObject);
      }
    }
    
    0 讨论(0)
  • 2020-11-27 05:26

    Check out lodash-deep’s deepHas https://github.com/marklagendijk/lodash-deep#_deephascollection-propertypath

    And this too https://github.com/danielstjules/hoops

    0 讨论(0)
  • 2020-11-27 05:27
    if (someObject.member && someObject.member.member &&
        someObject.member.member.member && someObject.member.member.member.value) ...
    

    or similarly:

    var val = foo.bar && foo.bar.jim && foo.bar.jim.jam && foo.bar.jim.jam.value;
    

    This will not 'work' if any particular value happens to be null, false, 0, or "" (an empty string), but with the possible exception of the final value, this seems unlikely to be the case.

    Also, note that typeof ____ !== "undefined" is not the correct test to see if an object has a property. Instead you should use ___ in object, e.g. if ("member" in someObject). This is because you can set a property to an explicit value of undefined, which is different from removing it with delete someObject.member.

    0 讨论(0)
  • 2020-11-27 05:27

    Theres a safeRead function defined here on thecodeabode which allows a safeRead of nested properties i.e.

    safeRead(foo, 'bar', 'jim', 'jam');
    

    if any of the properties are null or undefined a blank string is returned - useful for formatting / string interpolation

    0 讨论(0)
提交回复
热议问题