Search code examples
javascriptundefinedhasownproperty

Using hasOwnProperty dynamically for error 'Cannot read property '...' of undefined'


I am getting the error

Cannot read property 'billingDate' of undefined

installment here is undefined

response.detailsResponse.installment.billingDate

I want to use hasOwnProperty but in a dynamic way, like I pass the path and the object (to check against) to a function, it does the following checks and return true or false.

function checkProperty(path, obj){
    //assuming path = response.detailsResponse.installment.billingDate
    //assuming obj = response [a json/object]

    //check if response.detailsResponse exists
    //then check if response.detailsResponse.installment exists
    //then check if response.detailsResponse.installment.billingDate exists
}

The path length/keys can vary.

The code has to be optimized and generic.


Solution

  • You can rewrite the function in the following way

        function checkProperty(path,obj){
          splittedarr = path.split('.');
          var tempObj = obj;
          for(var i=1; i<splittedarr.length; i++){
            if(typeof tempObj[splittedarr[i]] === 'undefined'){
             return false;
            }else{
             tempObj = tempObj[splittedarr[i]];
            }
          }
          return true;
         }
    

    Starting from index 1 as in accordance to your example it seems like response in response.detailsResponse.installment.billingDate for path is same as the obj passed to the function.