2

I have a javascript array of multiple objects like the one bellow :

var myArray = [{

year:'2015',
model:'BMW',
used:false,
extras: [{buckets:'no',sportWheels:'yes'},{buckets:'no',sportWheels:'yes'}],
color:'blue'

.....

}];

What i am trying to do is to loop this array and pass the results into a list, something like this :

$.each(myArray, function(i, e){
var year = myArray[i].year;
var model = myArray[i].model;
var used = myArray[i].used;
var color = myArray[i].color;
var extras = myArray[i].extras; 

$('.list').append(year+model+used+color);
});

Everything goes well till i want to gather the results of extras. I dont know what to do can anyone suggest something. I thought about a second loop but doesnt work!!!

1
  • 1
    A nested loop should work just fine. Please post what you tried and we'll figure out what you did wrong. Commented Feb 5, 2015 at 1:42

1 Answer 1

5

do each loop for myArray[i].extras

    $.each(myArray, function(i, e){
        var year = myArray[i].year;
        var model = myArray[i].model;
        var used = myArray[i].used;
        var color = myArray[i].color;
        var extras = myArray[i].extras; 
        var str=''; 
        $.each(myArray[i].extras, function (index, data) {
            // alert(data.buckets);
            str+='<div>' + year + model + used + color + data.buckets + data.sportWheels +'</div>';
        })
        $('.list').append(str);
        //$('.list').append(year+model+used+color);
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Yes i tried this but the problem is that i have more than one model in my array the code i wrote here is a sample and if you append into list like you did here in your example appending more lists than the data that exist , do more looping
change var str; to var str=''; undefined will be gone. it is my pleasure to help you.
You're the best buddy , really thank you, you rescued me!!! Have a nice time. bye :) :)
it is my pleasure to help you.

Your Answer

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.