-1

I have a JSON object:

{
"KF":
    [{"name":"NATALIA","th":10},{"name":"STEVE","th":10}],
"LC" : 
    [{"name":"RANDY","th":10},{"name":"EVAN","th":10}],
"EL":
    [{"name":"SCOTTY","th":10},{"name":"SKIP","th":10}] 
}

I'm trying to get the key values, loop through each one and append() the names to their corresponding div id's. The code I'm using:

$.getJSON("players.json", function(data){
    var clans = Object.keys(data);
        $.each(clans, function(i, clan){
            console.log(clan);
            $.each(data.clan, function(n, player){
                $('#' + clan).append(player.name+' <span class="badge">'+player.th +'</span><br>\n');
            });
        });
    }); 

I'm getting an error: Uncaught TypeError: Cannot read property 'length' of undefined, but I'm not sure why.

If I explicitly tell the data object what I want it works... for example:

$.each(data.EL, function(n, player){
    $('#EL').append(player.name+' <span class="badge">'+player.th +'</span><br>\n');
});
$.each(data.KF, function(n, player){
    $('#KF').append(player.name+' <span class="badge">'+player.th +'</span><br>\n');
});
$.each(data.LC, function(n, player){
    $('#LC').append(player.name+' <span class="badge">'+player.th +'</span><br>\n');
});

But this obviously isn't practical. Not sure what I'm doing wrong?

Ponyboy
  • 956
  • 9
  • 16
  • I assumed this would be a duplicate, but when you don't know the problem it's hard to know what to search for. – Ponyboy Apr 21 '15 at 16:01

1 Answers1

1

In order to use the value of clan when accessing data, you need to use the [] syntax because it's dynamic.

Because of this, data.clan is undefined.

$.each(data[clan], function(n, player){
//         ^^^^^^ [] notation for a dynamic key
MrCode
  • 63,975
  • 10
  • 90
  • 112