0

So as the example below show I want to loop through an array inside an jQuery plugin that I'm trying to build. It's not working so can somebody help me with this.

$.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(){}
 } 
 ]
};
Jay Blanchard
34.5k17 gold badges82 silver badges130 bronze badges
asked Apr 10, 2014 at 20:25

1 Answer 1

1

It looks like your problem is due to the object keys not being unique.

Do JSON keys need to be unique?

You can use this:

$.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

answered Apr 10, 2014 at 20:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.