1

I've looked a lot of examples but I couldn't find anything to solve my problem. I have json array with following format ;

{ "value" : [
    { "...some variables...",
      "comments" : [
        { "user_name"   : "arascanakin",
          "picture_url" : "...some url..."
        }
      ],
      "error" : false,
      "msg"   : "some message"
    }

P.S. There may be syntax errors, I've written the JSON array manually. It's right.

I have the following jQuery to iterate over arrays:

$.each($task_array, function (i, task) 
{
    // some stuff
    $.each(task.comments, function(i, $task_comment)
    {
        // some stuff
        // $task_comment is undefined here
    }); 
});

The problem is task.comments is undefined when I set each comment element to $task_comment.

Any ideas to solve this problem? It seems correct to me but I read that JavaScript doesn't allow multidimensional arrays.

5
  • 1
    If your JSON data is correct, then your problem is not related to JSON but to how to access JavaScript objects/arrays. You are right, JavaScript does not have multidimensional arrays, but you can of course have arrays of arrays. There is not much to say here, really. If task.comments is an array, then $task_comment will be the value of the array entry: jsfiddle.net/7yJkG. It seems the data is not like you think it is, double check it. Commented Feb 28, 2012 at 16:54
  • have you tried classic javascript? somethink like tsk = task.comments; for(var i = 0; i < tsk.length; i++) { //do something with tsk[i]; } Commented Feb 28, 2012 at 16:56
  • I'm sending this json by json_encode($return) statement. I don't give json by manually. Commented Feb 28, 2012 at 17:01
  • $task_comment.user_name and $task_comment.content gives the right values, but I still get this error; Cannot read property 'length' of undefined line_no : second each iteration @FelixKling Commented Feb 28, 2012 at 17:05
  • Please create a jsfiddle.net demo with a more complete example (more data, more code). Commented Feb 28, 2012 at 17:16

1 Answer 1

1

I fiddled with your code and it works alright for me, once I fixed your json...

http://jsfiddle.net/zyBmn/1/

I wanted to post the json here, but it's not formatting correctly... see the fiddle

edit: tidier fiddle with several comments: http://jsfiddle.net/zyBmn/3/

Sign up to request clarification or add additional context in comments.

Comments

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.