JoelP
JoelP

Reputation: 439

Get JSON array name?

Let's assume I have a json file like this:

{
  "tools":[
  {
    "category1":[
    {
      "name":"Sample Name",
      "description":"Sample Desc",
      "version":"4.1"
    },
    {
      "name":"Another sample name",
      "description":"Another sample desc",
      "version":"1.0"
    }
    ],
    "category2":[
    {
      "name":"Just sample name",
      "description":"Description here",
      "version":"3.0-beta"
    }
    ]
 }
 ]
}

Now I access the file using the $.getJSON() method and a for-loop in it. The goal is to put every category name (category1, category2) into a <h1>-element, then just display the contents of this category. The problem here is that I don't know the category names as they are dynamically changed from time to time. What I've tried so far:

$.getJSON('tools.json', function(data) {
  var output="";
  for (var i in data.tools) {
    output+="<h1>" + data.tools[i] + "</h1>";
     for (var k in data.tools) {
       output+="data.tools[i][k].name - data.tools[i][k].desc - data.tools[i][k].version";
  }
}

This doesn't work because property name is undefined. So now my question is how do I get the category name and then access all of its content without knowing the name of it?

Thanks in advance.

Upvotes: 0

Views: 851

Answers (1)

foxygen
foxygen

Reputation: 1388

Try using Object.keys()

   var categories = Object.keys(data.tools[0]);

    $.each(categories, function(index, category){

        $('body').append('<h1>' + category + '</h1>');

        var items = data.tools[0][category];

        $.each(items, function(i, obj){

            $('body').append(obj.name + '<br>');

        });

    });

Here is a fiddle:

http://jsfiddle.net/mf99setb/

Upvotes: 1

Related Questions