EricBellDesigns EricBellDesigns - 2 years ago 81
Javascript Question

using jQuery to iterate through an array to create links

I am attempting to loop through a very simple array in order to create a menu. I have been all around the solution, but have yet to nail it down.

Here's my script:

var json_data = [["Womens","/womens"],["Best Sellers","/best-sellers"]];
var json_length = json_data.length;
var inner_length = 0;

for (var i = 0; i<json_length; i++)
inner_length = json_data[i].length;
for( var j = 0; j<inner_length; j++ ){

var innerData = json_data[i][j];

var data = '<a href="' + json_data[j][1] + '">' + json_data[j][0] + '</a><br/>';




Basic HTML:

<div id="content">

When I move the code to append to my div within the first for loop (rather than the second), the second object's data is shown twice rather than the first then second. The current code shows both the first and second object's data, but duplicates it due to being inside the second for loop. I'm sure there is a simple solution, but I am at a loss of ideas.

Answer Source

You can iterate through the array more easily using forEach():

json_data.forEach(function(item) {
  var data = '<a href="' + item[1] + '">' + item[0] + '</a><br/>';


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download