Check if object member exists in nested object

后端 未结 8 975
花落未央
花落未央 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: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.

提交回复
热议问题