christopher.web christopher.web - 27 days ago 16
Javascript Question

Getting JSON object titles

I've tried searching on here, but I can't figure this out.

I'm trying to do an each function that grabs each title of the object, my json is.

{"games":{
"featured": [
{
"game_id": "2"
},
{
"game_id": "15",
}
],
"popular": [
{
"game_id": "2"
}
],
"new": [
{
"game_id": "2",
},
{
"game_id": "15",
},
{
"game_id": "1",
}
]
}}


My JS is:

$.getJSON("apilink",
function(data) {
$.each(data.games, function(i,category){
alert(category[0]);
});
});


I'm obviously trying to rotate through featured, popular and new. What am I doing wrong? Thanks!

Answer

You can use nested $.each() calls to iterate each array of objects at category : property name of "games" property of data

var data = {
  "games": {
    "featured": [{
      "game_id": "2"
    }, {
      "game_id": "15",
    }],
    "popular": [{
      "game_id": "2"
    }],
    "new": [{
      "game_id": "2",
    }, {
      "game_id": "15",
    }, {
      "game_id": "1",
    }]
  }
};

$.each(data.games, function(i, category) {
  console.log(i + ":");
  $.each(category, function(key, obj) {
    console.log(obj)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>