EasyBB
EasyBB

Reputation: 6574

Iterating an array that is nested with an object key

var html = {
easyBB :   
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb:
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB2:
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb2 : 
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB3 :
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb3 : 
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png']
};
 var cont = document.getElementById('container');
  for(var key in html){
   for(var i =0;i<key.length;i++ ){
     var name= '<span class="name">'+html[key][0] +'</span>',
     link = '<span class="url"><a href="'+html[key][1]+'">'+html[key][1] +'</a></span>',
     image = '<img src="'+html[key][2]+'" title="'+html[key][0]+'" />';        
     cont.innerHTML= '<div class="wrapper">'+ name + '<br />'+image+'<br />'+link+'</div>';
      i++;
   }
 }

I am trying to iterate over the arrays in each key of the HTML object I created problem is not sure how to do this I've tried multiple ways now and I believe (since I am posting) I am doing this all wrong. I've also tried doing: html[key[i]][0] though of course I get an error of i is not defined. Any suggestions what I am doing wrong, as of right now it is only posting one array to the html.

Upvotes: 0

Views: 58

Answers (3)

Stuart
Stuart

Reputation: 9868

The problem is not the iteration, it's the line

cont.innerHTML = ...

which is replacing the content each time the loop iterates so that you only see the final item ("AvacWeb3").

Change that to

cont.innerHTML += ...

and get rid of the for (var i =0 ... loop which isn't needed. (jsfiddle)

Upvotes: 4

Michiel Dral
Michiel Dral

Reputation: 4074

You should do html[key][i][0].
And also you should do what Trevor said, html[key].length instead of key.length.

Make yourself easy by assigning html[key] to var currentkey for example, easier to keep track on.

Also, look into array.forEach, just for fun ;)

Upvotes: 0

Trevor Dixon
Trevor Dixon

Reputation: 24392

for(var i = 0; i < html[key].length; i++){
...

Upvotes: 0

Related Questions