0

after an ajax cal I can print the following result:

Array(3)
0: [{Col1: "Value", Col2: "Value" }]
1: [{Col1: "Value", Col2: "Value" }]
2: [{Col1: "Value", Col2: "Value" }]

What I'm trying to do is to populate a table with a for loop. Here is what I'm trying to use.

$.ajax({
    url: "apiurl",
    data: {},
    method: "GET",
    success: function (data) {
        var json = data;
        var html = "";

        for (var x = 0; x < json.length; x++) {
            html += "<tr><td>" + json[x].Col1+ "</td><td>" + json[x].Col2+ "</td></tr>";
        }

        $('#Table').html("");
        $('#Table').html(html);         
    }
});

This code doesn't populate the table but if I do this change:

var json = data[0];

The table is populated with the values from the array with index 0, so my question is, what can I do to populate my table with the values of all the index.

User1899289003
  • 850
  • 2
  • 21
  • 40
  • `data` has an array at each index. Use `json[x][0].Col1` instead of `json[x].Col1` Or, use `var json = data.flat()` and keep the existing loop – adiga Jan 11 '21 at 08:19

1 Answers1

1

It seems like your data is an array of arrays. You need to flatten this:

var json = data.map((entry) => entry[0]);

You can also use the .flat() method:

var json = data.flat();
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38