0

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/>';

        //alert(data);

        $("#content").append(data);

    }
}

Basic HTML:

<div id="content">
</div>

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.

4
  • Here's a Fiddle: jsfiddle.net/79k32o1j/3 Commented May 10, 2016 at 21:37
  • 2
    That is not JSON, that is a two dimensional array. Commented May 10, 2016 at 21:38
  • why are you using two loops? Commented May 10, 2016 at 21:40
  • @Kilmazing you're correct sorry I should have explained better. The JSON will be in the same format once it's ready. Commented May 10, 2016 at 21:45

2 Answers 2

3

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/>';
  $("#content").append(data);
});

Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much @RickHitchcock! This works perfectly for me!
1

Updated your fiddle, removed the unnecessary loop:

https://jsfiddle.net/79k32o1j/4/

for (var i = 0; i<json_length; i++) {
    var data = '<a href="' + json_data[i][1] + '">' + json_data[i][0] + '</a><br/>';
    $("#content").append(data);
}

1 Comment

Thank you for your time and effort. This is the exact solution I was looking for! Rick's answer works a bit better for my case, but I wish I could mark both answers correct.

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.