0

Here I'm looping through an object and retrieving the key:value pairs and placing them in a table

obj = clickedRecord.toJSON(); //gets record from 
                              //separate table and converts to JSON format
var array=[];
for(key in obj) {
   if(obj.hasOwnProperty(key)) {
      array.push(
         '<table id="myTable">' +
             '<tr>' +
               '<td>' + key + '</td>' +
               '<td>' + obj[key] + '</td>' +
             '<tr>' +
         '</table>''
      );
   }
}

The output of which is:

ID 100
,
Name Billy
,
Address 525 Park Lane
,

Is there a cleaner way to dynamically construct a table using a javascript Object, as well as omit the commas from the returned data?

3
  • Not really, unless you want to use jquery or Just straight DOM manipulation. Which is basically the same just with a couple of less lines. Commented Sep 5, 2014 at 16:58
  • 1
    Your output seems to be a string presentation of an array. Add .join('') to the end of the output expression. Commented Sep 5, 2014 at 16:58
  • Thanks @Teemu the .join('') did the trick. I just realized I'm making a table for each iteration of the loop-no bueno Commented Sep 5, 2014 at 17:03

1 Answer 1

1

Something like this:

   var table = document.createElement('TABLE');
   table.setAttribute("id", "myTable");

   for(key in obj) {
       var tr = document.createElement('TR');
       table.appendChild(tr);

       var td = document.createElement('TD');           
       td.appendChild(document.createTextNode(key));
       tr.appendChild(td);

       var td2 = document.createElement('TD');           
       td2.appendChild(document.createTextNode(obj[key]));
       tr.appendChild(td2);
   }
Sign up to request clarification or add additional context in comments.

1 Comment

@ClayBanks No problem, glad to be of help.

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.