简体   繁体   中英

javascript object undefined error

I have Dynamic AJAX JSON Response object Data variable

 var Data = {"categories":
    [
      {"Id":"2","CategoryName":"Womens"},
      {"Id":"3","CategoryName":"Mens"},{"Id":"4","CategoryName":"Kids"},
      {"Id":"5","CategoryName":"Home"},{"Id":"6","CategoryName":"Health and Beauty"},
      {"Id":"7","CategoryName":"Seasonal Events"},{"Id":"10","CategoryName":"Model Shots"},
      {"Id":"11","CategoryName":"Product Shots"},      
      {"Id":"12","CategoryName":"Accessories"},
      {"Id":"13","CategoryName":"Tops"},{"Id":"14","CategoryName":"Spuds"},
      {"Id":"15","CategoryName":"EVIAN"}
     ],
         "brands_cat":{
             "_bandCount":{"171": "BrandId" : "171", "ArchiveName": "HP",     
             "img_from_archive":"7"}
                      }
    }
  };

When i used in loop and check undefined , works fine

for(var i in Data.categories){
   if(typeof Data.categories[i] == 'undefined'){
       alert(i+"Cat undefined");
   }
}

But when i used typeof to check undefined ,

for(var i in Data.categories){
       if(typeof Data.brands_cat._catCount[i].total == 'undefined'){
           alert(i+"Cat total undefined");
       }
    }

And it gave error

TypeError: Data.brands_cat._catCount is undefined

Is it possible to check multilevel JSON object undefined with typeof keyword

There is no _catCount in brands_cat . So, change it like this

if (Data.brands_cat.hasOwnProperty("_catCount")) {
    for (var i in Data.brands_cat._catCount) {
        if(typeof Data.brands_cat._catCount[i].total == 'undefined') {

This code will iterate through _catCount only if it is found

Within the example object you gave brands_cat does not always exist. When you iterate you need to check for the existence of that first prior to checking anything further down the object tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM