Ad

Convert AJAX Response Of Objects Array To A JSON Object

- 1 answer

I have a sample endpoint here which has a JSON data, but for any reason I do not understand why it does return [object Object].

Mock API

I have a previous code which was a bit confusing, but luckily I saw another answer that was clearer.

function generateTable(data, selId){

    var cnt = "<table border=1>";

    cnt += "<tr>";
    $.each(JSON.parse(data), function(key,value){
       cnt += "<td><strong>" + key + "</strong></td>";
    });
   cnt += "<tr>";

   /* cnt += "<tr>";
   $.each(obj, function(key,value){
       cnt += "<td>" + value + "</td>";
   });
   cnt += "<tr>"; */ This part was commented because the conversion above does not work.
   cnt += "</table>";

   $(selId).html(cnt);

}

function createTableData(APIurl, selId){
    $.getJSON("http://jsonplaceholder.typicode.com/posts", function(data){
          generateTable(data, selId);
    });
}

When I try to alert the data returned, it return [object Object], [object Object], ... and so on. How do I convert the JSON data from the API to an array where I can access inside my generateTable function? Thanks for the help.

Ad

Answer

You need to iterate over the array

var cnt = "<table border=1>";
for (var i=0, len=data.length; i<len; i++){
    var row = data[i];
    cnt += "<tr>";
    $.each(row, function(key,value){
       cnt += "<td><strong>" + key + "</strong></td>";
    });
   cnt += "</tr>";
}
cnt += "</table>";
Ad
source: stackoverflow.com
Ad