4

Say I have JSON data as below:

var db=[
        {"name":"John Doe","age":25},
        {"name":"John Doe 2","age":21}
       ]

I know how to retrieve data from the JSON object using js/jquery. What I need is to get the value of the labels, i.e. I want to retrieve the "name" and the "age" from the object. I don't actually want to retrieve the values "John Doe" and 25 (I can already do that), instead I want the labels.

Say the JSON object has about 5 data with 10 fields each. I need to display the JSON in table form dynamically which I can already do. Since the JSON may be any set of values, I won't know what label to put in the <th></th> cells of the table. So I need a way to get the labels.

Using a pseudo code:

var db=[
        {"name":"John Doe","age":25},
        {"name":"John Doe 2","age":21}
       ]    
for i in db{
    for j in db[i]{
          console.log(db[i][j].label+":"db[i][j])
    }  
}
//db[i][j].label doesn't really work

The output should be:

name: John Doe

age: 25

name: John Doe

age: 21

Is there a JavaScript or jQuery function to do so or some other method to retrieve the required data?

xxx
  • 1,153
  • 1
  • 11
  • 23
Nisbaj
  • 80
  • 1
  • 2
  • 7

3 Answers3

5

You're already fetching the property name (which you are calling "label"). You need it to get the property's value out of the object.

So, it's just j.

console.log(j + ":" + db[i][j]);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Once loaded the JSON data is just an object (in your case an array of objects). You can just iterate over the properties/keys of each single object.

e.g.

$.each(db, function(index, object) {
    for (var property in object) {
        var val = object[property];
        // do stuff
        console.log("property: " + property + ", val: " + val);
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/5hkr8k2x/

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
1

You could look at using the jQuery.each function:

$.each(db, function(index, record) {
    $.each(record, function(key, value) {
        console.log(key + ': ' + value);
    });
});
Andy
  • 4,901
  • 5
  • 35
  • 57