Rich
Rich

Reputation: 1156

Using the each function within getJSON returns undefined

I'm using jQuery's getJSON method to retrive and parse a simple JSON file, but when I output the values onto my page it's displaying as undefined

$.getJSON( 'js/example.json', function ( data ) {

    var output = '';

    $.each( data.exercises, function ( index, exercise ) {
        output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';
    });

    $( '#example' ).html( output );

});

example.json

{

    "exercises" : [

        {
            "name" : "Squats",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        },
        {
            "name" : "Bench",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        },
        {
            "name" : "Rows",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        }

    ]


}

I think the error might lie within my each function, but I haven't been able to identify it yet. Any ideas?

Upvotes: 0

Views: 148

Answers (2)

Amundio
Amundio

Reputation: 416

Your exercise work is an array, need another loop

$.each( data.exercises, function ( index, exercise ) {
    $.each(exercise.work, function (index, work) {
         console.log(work);
    });
});

Upvotes: 2

Paul Roub
Paul Roub

Reputation: 36438

This:

output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';

assumes your JSON looks like:

"exercises" : [
  {
    "name" : "Squats",
    "work" : 
      {
        "weight" : 135,
        "reps" : 5
      }
  },

When in fact work is an array in each case.

You want something like:

$.each( data.exercises, function ( index, exercise ) {

   $.each( exercise.work, function( index, workout ) { 
      output += '<li>' + workout.weight + ' x ' + workout.reps  + '</li>';
   });

});

Upvotes: 1

Related Questions