0

Trying to retreive some JSON from a server which looks like the following

json  =  {"posts":[{
      "post":{
        "title" : "foo", 
            }
      },
      {
      "post":{
        "title" : "bar", 
            }
      },
]}

And I am trying to loop over like

for(var i = 0; i < json.length; i++) {
    var obj = json[i];
    console.log(obj.posts.post.title); 
}

Which doesn't work.

And I've tried

var totalMessages = Object.keys(json.posts).length;

for(var i = 0; i < totalMessages; i++) {
        console.log(json.posts.post.title); 
    }

Which also doesn't work

How can I loop through the above json and log the titles?

Thanks

1 Answers1

1

json  =  {
     "posts":[{
     "post":{
        "title" : "foo", 
            }
      },{
      "post":{
        "title" : "bar", 
            }
      },
]}

json.posts.forEach(postContainer => { 
     let post = postContainer.post;
     console.log(post.title); 
});

You're forgetting that posts is an array of unnamed objects.
Those unnamed objects have a property called post.
That property contains the post info you need.
You only need to go "one layer deeper"

Basically, your structure is, json.posts[arrayindex].post.title, in your code you assumed post was at the position of arrayIndex, and title at the position of post.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133