1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

There might have _catCount, it is category items count, so how i can prevent from error
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.