0

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?

2
  • Your json is not valid... jsonlint.com Commented Apr 28, 2014 at 2:55
  • 1
    @superUntitled It's invalid, but it also isn't JSON. JSHint or JSLint would be more fitting suggestions. Commented Apr 28, 2014 at 2:58

1 Answer 1

3

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.

0

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.