使用jQuery循环遍历多维数组

时间:2014-04-10 20:25:52

标签: jquery loops each

因此,下面的示例显示我想循环遍历我正在尝试构建的jQuery插件中的数组。它没有用,所以有人可以帮我解决这个问题。

$.each(defaults.garage, function(i, value){

    $.each(value.cars, function(i2, value2){

        alert(value2.model);

    }); 

});

$.fn[pluginName].defaults = {
      garage:[
            {
                name: '',
                country:'',
                cars:[
                        {
                            model: '',
                            year:''

                        },
                        {
                            model: '',
                            year:''

                        }

                ],
                hook: function(){}
            }       
        ],
        garage:[
            {
                name: '',
                country:'',
                cars:[
                        {
                            model: '',
                            year:''

                        },
                        {
                            model: '',
                            year:''

                        }

                ],
                hook: function(){}
            }       
        ]
};

1 个答案:

答案 0 :(得分:1)

看起来您的问题是由于对象键不是唯一的。

Do JSON keys need to be unique?

您可以使用:

$.each(garages, function(i,v){
    $.each(garages[i].cars, function(i2, v2){
        alert(garages[i].cars[i2].model);
    })
})

garages = [
    {
        name: '',
        country: '',
        cars:[
            {
                model: 'BMW',
                year: ''
            }
        ],
        hook: function(){}
    }

    {
        name: '',
        country: '',
        cars:[
            {
                model: 'Honda',
                year: ''
            }
        ],
        hook: function(){}
    }

]

here is a fiddle