在json子数组上运行每个循环

时间:2013-03-25 23:10:23

标签: javascript ajax json

我有一个带有子数组的json数组,其格式如下:

[{"id":"188","stars":"2","staryes":"2","starers [{"starfirstname":"Name1","starlastname":"Name1","staruser":"1"},
{"starfirstname":"Name2","starlastname":"Name2 ","staruser":"3"}],"time":"1364151043","postedby":"43","text":"TEST","firstname":"Name3","lastname":"Name3","picture":"806243.jpg"}]

我可以通过执行以下操作在整个阵列上运行循环:

 $.each(data, function(i, data) { //function })

但我无法弄清楚如何在子阵列'starers'上运行循环

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

假设你的JSON确实有效,它是一个常规的JavaScript数组:

for (var i = 0; i < thing.starers.length; i++) {
    var starer = thing.starers[i];

    ...
}

答案 1 :(得分:0)

.each回调中,data将是恰好具有starers属性的每个对象。因此,请从那里再次循环(为了清楚起见,我将data重命名为item

$.each(data, function(i, item) { 
    $.each(item.starers, function(i, starer) { 
        // do something
        // e.g. alert(starer.starfirstname);
    });
});