1

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.

1
  • Check the console.log() instead of alert. And it looks like you've got an object back already, so you don't need to JSON.parse() it. Commented Jan 11, 2016 at 2:14

1 Answer 1

1

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

3 Comments

Thanks. I try to debug that one. It works for the console. However, it does not reflect in the HTML.
You still need to use the $(selId).html(cnt); i just included the part that needed edits.
That one works like a charm. Now, I am trying to loop once over the keys of the object. However it returns 0,1,2,3... How do I loop over "name, "age", etc."? I tried using Object.keys but it didn't work. Thanks. @GabyakaGPetrioli

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.