Fizzix
Fizzix

Reputation: 24395

How to loop over an array within a JavaScript object?

Very new to JavaScript objects, so I am not to sure how to go about doing this.

Within my object, I have an array called myArray. I am attempting to loop over it to print out everything on the page. Usually there is a a lot more data within the object, but it has been removed for this example.

This is my object:

var data = [
    {
        myArray:
        {
            name: 'name1',
            code: 'code1',
            data: {
                date: '20-Apr-2014',
                signal: 'signal1'
            }
        },
        {
            name: 'name2',
            code: 'code2',
            data: {
                date: '21-Apr-2014',
                signal: 'signal2'
            }
        }
    }
]

This is my iteration code:

var arrayLength = data.myArray.length - 1;
for (var i = 0; i <= arrayLength; i++) {
    var name = data.myArray[i].name;
    console.log(name);
}

My code above should produce the results in the console name1 and name2. However, I am getting an error of Cannot read property 'length' of undefined.

How can I change my above code to do this?

Upvotes: 0

Views: 66

Answers (1)

Ray Toal
Ray Toal

Reputation: 88478

Your object should use brackets for the array:

var data = {
    myArray: [
    {
        name: 'name1',
        code: 'code1',
        data: {
            date: '20-Apr-2014',
            signal: 'signal1'
        }
    },
    {
        name: 'name2',
        code: 'code2',
        data: {
            date: '21-Apr-2014',
            signal: 'signal2'
        }
    }
    ]
}

I've also removed the outermost brackets, since it would appear from your question that your intent was to have a single array inside an object, and not an array of arrays.

With the object above, your iteration code will work fine.

Upvotes: 3

Related Questions