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.

1
  • 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 Commented Jan 11, 2021 at 8:19

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.