Check if object member exists in nested object

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

    In general, you can use if(property in object), but this would be still cumbersome for nested members.

    You could write a function:

    function test(obj, prop) {
        var parts = prop.split('.');
        for(var i = 0, l = parts.length; i < l; i++) {
            var part = parts[i];
            if(obj !== null && typeof obj === "object" && part in obj) {
                obj = obj[part];
            }
            else {
                return false;
            }
        }
        return true;
    }
    
    test(someObject, 'member.member.member.value');
    

    DEMO

提交回复
热议问题