Search code examples
javascriptjqueryjsongetjson

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?


Solution

  • Your exercise work is an array, need another loop

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