Thomas
Thomas

Reputation: 415

Properly loop through JSON with jQuery

I have the following JSON:

{
  "status" : "success",
  "0": { 
    "link"  : "test1",
    "img"   : "test2",
    "title" : "test3"
  },
  "1":{
    "link"  : "test4",
    "img"   : "test5",
    "title" : "test6"
  }
}

Obviously 0 and 1 are objects themselves and I would like a proper way to loop through all data in this object, the 'status', '0', and '1'. What I have right now (and works) is below, I know there has to be a better method to see if the element is just one deep, such as 'status' or if it's an object, such as '0' and '1':

// Prints the link from '0' and '1'
$.each(test, function(){
if(this == '[object Object]')
 alert(this.link);
});

Upvotes: 1

Views: 1233

Answers (1)

Jaka Jančar
Jaka Jančar

Reputation: 11606

for (var propName in object) {
    var prop = object[propName];
    if (typeof prop == "object")
        ...
}

Upvotes: 2

Related Questions