Reputation: 3145
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.
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!
Upvotes: 0
Views: 40
Reputation: 73231
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;
}
};
Upvotes: 3