0

I'm trying to make a function that iterates through all the objects in an array returned to me by the server. Here's the structure that is listed when I console.log my response.

structure

Now I made a javascript function that looks like this—

var createPosts = ((data) => {
var postsArrayLength = data.response.total_posts;

    for ( i = 0; i < postsArrayLength; i++ ) {
        //for each post create a div
        var postDiv = document.createElement('div');
        postDiv.className = 'post ' + data.response.posts.postsArrayLength[i].type;
    }
});

and I'm receiving this error—

Uncaught TypeError: Cannot read property '0' of undefined

It seems to only be giving me this error when I try to get an object that has an integer as its name.

Is there a way to deal with this? Or am I going about this completely wrong? Thanks!

2
  • 3
    Change data.response.posts.postsArrayLength[i].type to data.response.posts[i].type Commented Sep 3, 2016 at 16:33
  • Thank you, this worked! Didn't realise I could access the array directly. Commented Sep 3, 2016 at 16:37

1 Answer 1

3

Rewrite your function to something like this:

var createPosts = data => {
    for ( i = 0; i < data.response.posts.length; i++ ) {
        //for each post create a div
        var postDiv = document.createElement('div');
        postDiv.className = 'post ' + data.response.posts[i].type;
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Sure, still a valuable answer. +1. ;)

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.