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

前端 未结 16 2499
野性不改
野性不改 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:19

    This is a common issue when working with deep or complex json object, so I try to avoid try/catch or embedding multiple checks which would make the code unreadable, I usually use this little piece of code in all my procect to do the job.

    /* ex: getProperty(myObj,'aze.xyz',0) // return myObj.aze.xyz safely
     * accepts array for property names: 
     *     getProperty(myObj,['aze','xyz'],{value: null}) 
     */
    function getProperty(obj, props, defaultValue) {
        var res, isvoid = function(x){return typeof x === "undefined" || x === null;}
        if(!isvoid(obj)){
            if(isvoid(props)) props = [];
            if(typeof props  === "string") props = props.trim().split(".");
            if(props.constructor === Array){
                res = props.length>1 ? getProperty(obj[props.shift()],props,defaultValue) : obj[props[0]];
            }
        }
        return typeof res === "undefined" ? defaultValue: res;
    }
    

提交回复
热议问题