选择其值为多维JSON对象中的数组的单个键,并循环遍历该数组

时间:2015-06-11 17:54:11

标签: javascript jquery arrays json

编辑:我的问题是,在为函数appendAllComments提供参数subid时,当我发出警告subid时,它会说例如77确实存在于JSON对象中。所以:

global_save_json.input == global_save_json.subid == global_save_json.77 (?) or "77"

然而它出于某种原因返回undefined?这是一个数字与字符串问题或什么?

我需要选择comments对象的一个​​键,然后遍历数组。

来自fresh_posts.php

{ 
    "posts":{
        "5": {
            "id":"5",
            "image":"link.jpg",
            "submitter":"4322309",
            "views":"3"
        },
        "2": {
            "id":"2",
            "image":"link.jpg",
            "submitter":"4322309",
            "views":"5"
        }
    },

    "comments":{
        "2": [{
            "id":"1",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"2"
        },
        {
            "id":"2",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"2"
        }
    ],
        "5": [{
            "id":"3",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"5"
        }]
    }
}

最初有:

$.getJSON('fresh_posts.php',function(data){
    global_save_json = data.comments;

现在我需要在赛道后面再次使用global_save_json

$('.main').on('click', '.new-comments', function(e) {

      var fullid = e.target.id;
      var subid = fullid.substring(8); // subid = number like 75

      function appendAllComments(input) {

        for (var commentList in global_save_json.input) {
          $.each(commentList, function(index, c) {
            // i need to set variables, i.e. var id = the value of "id" key in the object in the array of comments
          })
        }
      }

      appendAllComments(subid);

 })

我试图重复使用之前的for循环,但它无法正常工作,我被卡住了 - 请参阅循环内部的注释以了解我正在尝试做什么

0 个答案:

没有答案