在jQuery中循环访问JSON数据

时间:2015-02-11 13:52:15

标签: jquery json

这是我的JSON数据:

{
    "comments": [{
        "id": "1",
        "message": "Finish as soon as possible! Cibai!",
        "task_id": "1",
        "user_id": "1",
        "date_created": "2015-02-06 00:00:00.000000"
    }, {
        "id": "19",
        "message": "Another message",
        "task_id": "1",
        "user_id": "1",
        "date_created": "2015-02-10 00:00:00.000000"
    }, {
        "id": "20",
        "message": "Comment about the header",
        "task_id": "1",
        "user_id": "1",
        "date_created": "2015-02-09 00:00:00.000000"
    }],
        "status": true
}

这是我的jQuery,问题是Iam在警报中变为空:

var ids = [];
$.each(e, function(i, item) {
    ids.push(item.id);
});
alert(JSON.stringify(ids));

由于

1 个答案:

答案 0 :(得分:3)

id属性是存储在comments数组中的对象的一部分。您需要循环遍历e.comments。此外,在您构建数组时,您可以使用map()代替each()

var ids = $.map(e.comments, function(item) {
    return item.id;
});
alert(JSON.stringify(ids));

Example fiddle