2

Get guys,

I've tried looking through a bunch of tutorials but I can't seem to find one that covers this in detail. Maybe somebody could point me int he right direction.

I have a .json file that looks like this:

{
    "users": [{
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Sabrina",
        "lastName": "Doe"
    }]
}

I want to run a .each loop and grab all of the users. Here's what I've tried:

$.getJSON("database.json", function(data) {
    $.each(data.users, function(key, val) {
        $('.dbUL').append('<li>' + key + ' : ' + val + '</li>');
    });
});

So it looks like it actually does spit out the array since I get an output of 0 : [object Object] and 1 : [object Object].

My question is, how do I dig into the array and actually spit out the objects that I have stored in my array?

MarioD
  • 1,703
  • 1
  • 14
  • 24

2 Answers2

4

Knowing the properties what you want get (fistName, lastName): jsBin

$.getJSON("database.json", function(data) {
    $.each(data.users, function(idx, val) {
        $('.dbUL').append('<li>' + val.firstName + ' : ' + val.lastName + '</li>');
    });
});

Not knowing the properties you want to get: jsBin

$.getJSON("database.json", function(data) {

    var LIhtml = "";

    $.each(data.users, function(idx, obj) { 

      LIhtml += "<li>";

      for(var key in obj){
        if(obj.hasOwnProperty(key)){
          LIhtml += obj[key]+" ";
        }
      } 

      LIhtml += '</li>';

    });

    $('.dbUL').append(LIhtml);
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

As far as I know there isn't a fancy way to grab the values of a "Hash" in JS like you do in Ruby, for example.

Why not just using something like this below?

$('.dbUL').append('<li>' + key + ' : ' + val.firstName + ' ' + val.lastName + '</li>');
leandroico
  • 1,207
  • 13
  • 17