frosty
frosty

Reputation: 2851

Looping over JSON object returning undefined for some elements

In my JSON object in posts.php I have two arrays, posts and comments. Here's an example (posts is just [...] for this example but comments has 2 example comments:

posts.php

{
    "posts": [{
        ...        
    }],
    "comments": [{
        "id": "1",
        "submitter": "",
        "time": "1433601171",
        "comment": "example comment",
        "score": "0",
        "postid": "1"
    }, {
        "id": "2",
        "submitter": "",
        "time": "1433601211",
        "comment": "another comment",
        "score": "0",
        "postid": "1"
    }]
}

Javascript:

$.getJSON('posts.php',function(data){
    data.comments.forEach(function(comment){
      var id = comment.id;
      var submitter = comment.submitter;
      var time = comment.time;
      var comment = comment.comment;
      var score = comment.score;
      var postid = comment.postid;

For some reason when I alert(score) and alert(postid) they are undefined, yet all the other variables contain the correct information. Why?

Upvotes: 1

Views: 56

Answers (3)

codingrose
codingrose

Reputation: 15709

It is happening because you are using same variable named comment for different purposes.

var cmt = comment.comment;

Statements accessing comment as object after statement

var comment = comment.comment;

will throw error.

Change variable name comment inside loop, and it will be working.

DMEO here.

Upvotes: 0

Pinguin895
Pinguin895

Reputation: 1011

for some reason javascript does not like the variable name "comment" in the function parameter, because you use it twice. If you rename the variable to c for example, it works.

data.comments.forEach(function(c){
      var id = c.id;
      var submitter = c.submitter;
      var time = c.time;
      var comment = c.comment;
      var score = c.score;
      var postid = c.postid;
})

Upvotes: 0

Tim
Tim

Reputation: 3803

You having the same variable name of comment

//original comment variable points to commnet.comment
var comment = comment.comment;
//comment get overwrite from the original commnet
//now comment points to comment.comment
var score = comment.score;
var postid = comment.postid;

This causes score and postid to be undefined, because now you are referring score as comment.comment.score which is undefined

Upvotes: 1

Related Questions