How to avoid 'cannot read property of undefined' errors?

前端 未结 16 2374
野性不改
野性不改 2020-11-22 06:02

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:



        
16条回答
  •  醉梦人生
    2020-11-22 06:20

    I answered this before and happened to be doing a similar check today. A simplification to check if a nested dotted property exists. You could modify this to return the value, or some default to accomplish your goal.

    function containsProperty(instance, propertyName) {
        // make an array of properties to walk through because propertyName can be nested
        // ex "test.test2.test.test"
        let walkArr = propertyName.indexOf('.') > 0 ? propertyName.split('.') : [propertyName];
    
        // walk the tree - if any property does not exist then return false
        for (let treeDepth = 0, maxDepth = walkArr.length; treeDepth < maxDepth; treeDepth++) {
    
            // property does not exist
            if (!Object.prototype.hasOwnProperty.call(instance, walkArr[treeDepth])) {
                return false;
            }
    
            // does it exist - reassign the leaf
            instance = instance[walkArr[treeDepth]];
    
        }
    
        // default
        return true;
    
    }
    

    In your question you could do something like:

    let test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
    containsProperty(test[0], 'a.b.c');
    

提交回复
热议问题