0

I have a very simple function that loops through some JSON data and adds the data to a list:

function printData(file) {
    $.getJSON('json/' + file, function(data) {
        for( var i=0; i <= data.agencies.length; i++ ) {
            $('#results').append(
                '<li class="group">' +
                    '<div class="agency-logo"><img src="images/agency_logos/' + data.agencies[i].logo + '" alt="' + data.agencies[i].name + '" /></div>' +
                    '<div class="agency-info">' + data.agencies[i].name + '<br />' +
                    data.agencies[i].address + '<br />' +
                    data.agencies[i].city + ', '  + data.agencies[i].state + ' '+ data.agencies[i].zip + '<br />' +
                    data.agencies[i].phone + '<br />' +
                    data.agencies[i].email + '</div>' +
                    '<div class="agency-desc">' + data.agencies[i].description + '</div>' +
                '</li>'
            );
        }
    });
}

JSON data:

{
"agencies" : [
    {
        "name"          : "Test Agency",
        "address"       : "283 Main Street",
        "city"          : "Danbury",
        "state"         : "CT",
        "zip"           : "06810",
        "phone"         : "(555) 555-5555",
        "email"         : "[email protected]",
        "description"   : "This is the description.",
        "logo"          : "logo.gif"

    },
    {
        "name"          : "Test Agency",
        "address"       : "100 Oak Street",
        "city"          : "Roseland",
        "state"         : "NJ",
        "zip"           : "06810",
        "phone"         : "(444) 444-4444",
        "email"         : "[email protected]",
        "description"   : "This is the description.",
        "logo"          : "logo.gif"
    }
]
}

Everything is working and outputting as it should, however I am getting a console error on whatever is the first item that I am outputting: (I assume that I would get error on each call, but the JS stops being parsed at the error.)

TypeError: 'undefined' is not an object (evaluating 'data.agencies[i].logo')

This is my first time trying out outputting via JSON, so I am sure that I am missing something.

2 Answers 2

1

Your JS is fine. It's your loop that is incorrect

for( var i=0; i <= data.agencies.length; i++ )

should be

for( var i=0; i < data.agencies.length; i++ )
                ^ notice this change

You're trying to access the logo property of a null object.

Edit

Arrays are 0 indexed. This means that the first element is accessed using 0:

data.agencies[0] // <- returns the first element in the array

However, the length property returns the number of elements in the array. In this case, the length is returning 2.

In your original loop for( var i=0; i <= data.agencies.length; i++ ) you'd get the following:

data.agencies[0]  // i is less than or equal to 2
data.agencies[1]  // i is less than or equal to 2
data.agencies[2]  // i is less than or equal to 2 and this returns null
Sign up to request clarification or add additional context in comments.

5 Comments

that's right your objects length is 2 but your first index is 0 since you only have 2 'agencies' the index 2 is undefined
Ah, thanks. I was assuming that the length of the array started at 0. Thank you.
@user3427302. The length of the array does start at 0. I've updated my answer
@jasonscript Right, so wouldn't that mean that an alternate solution would be to start the index at 1? I tested that as well and still throws the error. Any idea why? EDIT: This is answered below. Thanks.
@user3427302 if your started the index at 1 i=1; i<= data.agencies.length; i++ you'd get lots of errors :) You wouldn't get the first agency value (agencies[0]) because i is never 0. Then your loop would try to get agencies[1] and agencies[2] and you would have the same error as before
0

You are looping on an Array-based counting which starts by 0 . While the "Length" property is not a Zero-based counting property so it counts starting by 1.You need to do one of either modifications :

    for( var i=1; i <= data.agencies.length; i++ ) --> Works for looping thought non Zero-based data indexes 

OR

    for( var i=0; i < data.agencies.length; i++ )  --> Works for JSON and Array-Based

Edit : First example will not work with looping through Array-based data like JSON.

2 Comments

Thanks for the explanation. However, starting the index at 1 does not resolve the issue and it still outputs the error. It also outputs one less item than it should. Any idea why that would be?
Yes , Actually my answer isn't perfect when dealing with Array-Based content like JSON data .. as basically JSON is a piece of array and you need to deal with it the way you deal with arrays, starting index is 0 , so consider using my second example for your current problem where you need to start counting from 0 so that you can read index[0] inside your json array .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.