0

If I have an object with data structured like this:

 { key1: 1, key2: 2, key3: 3, key4: 4, key5: 5 }

how could I (using pure JS) turn this into a table that looks like this:

sample table format

(the css does not in any way have to look like this. It is simply the formatting I would like)

However, the data that would be put into the table will change, so how could I make that happen automatically?

yes it must be an object.

Thank you so much.

Things that will help:

  • how to add another row/column to a table
  • how to assign text value to each cell
  • how to create a loop that will be able to get the key and the key value of one of the sets in the object
  • if someone explained the main aspects of what this piece of code means:

 function tableCreate() {
    //body reference 
    var body = document.getElementsById("body");

    // create elements <table> and a <tbody>
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");
 
    // cells creation
    for (var j = 0; j <= 2; j++) {
        // table row creation
        var row = document.createElement("tr");

        for (var i = 0; i < 2; i++) {
            // create element <td> and text node 
            //Make text node the contents of <td> element
            // put <td> at end of the table row
            var cell = document.createElement("td");    
            var cellText = document.createTextNode("cell is row "+j+", column "+i); 

            cell.appendChild(cellText);
            row.appendChild(cell);
        }

        //row added to end of table body
        tblBody.appendChild(row);
    }

    // append the <tbody> inside the <table>
    tbl.appendChild(tblBody);
    // put <table> in the <body>
    body.appendChild(tbl);
    // tbl border attribute to 
    tbl.setAttribute("border", "2");
}
<div id="body"></div>

2
  • 1
    Have you looked at any documentation on javascript DOM manipulation methods? The code snippet you posted is pretty straightforward to understand if you look up the functions used in it. Commented Aug 7, 2018 at 5:52
  • I guess you have pretty much all it takes. All you need is iterate over your object keys and insert one <td> at a time. Commented Aug 7, 2018 at 5:53

3 Answers 3

1

All you need is both name of the key and value. You can use Object.entries()

var data = Object.entries(yourObject);

Loop through this data same as you did above, you can get both key and value.

function tableCreate(dataObj) {
    //body reference 
    var body = document.getElementsByTagName("body")[0];

    // create elements <table> and a <tbody>
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");
  
    var entries = Object.entries(dataObj);

    // cells creation
    for (var j = 0; j < entries.length; j++) {
        // table row creation
        var row = document.createElement("tr");

        // Form and set the inner HTML directly
        row.innerHTML = `<td>${entries[j][0]}</td>${entries[j][1]}<td></td>`;

        //row added to end of table body
        tblBody.appendChild(row);
    }

    // append the <tbody> inside the <table>
    tbl.appendChild(tblBody);
    // put <table> in the <body>
    body.appendChild(tbl);
    // tbl border attribute to 
    tbl.setAttribute("border", "2");
}

Sign up to request clarification or add additional context in comments.

1 Comment

yes, this is the way I wanted to go - thank you so much. I was stuck on the part of looping it because I kept getting an error thrown. Thank you.
0

The object that you are talking about is a json object I tell you that how to iterate in that kind of object. Let jsonobj is the object name

for (key in jsonobj){
       console.log (jsonobj[key]);}

Now you just have to display data in html tags. I hope rest of the code is not a big challenge for you.

Comments

0

You can try something like this:

Idea

  • You can create utility function to create row and cell. They are very generic and should be independent of passed data structure or logic to process.
  • Then you can create a wrapper function that will process the data in necessary format. They can have business logic if you wish to.

This was, you will have a more reusable code and more flexibility

function createTableFromObject(obj, selector) {
  var table = document.createElement('table');
  for (var k in obj) {
    table.appendChild(createRow([k, obj[k]]))
  }
  addToContainer(selector, table);
}

function createTableFromArray(arr, selector) {
  // You can add your logic here.
}

function createRow(values) {
  var row = document.createElement('tr');
  values.forEach(function(value) {
    row.appendChild(createCell(value))
  });
  return row;
}

function createCell(value) {
  var cell = document.createElement('td');
  cell.innerHTML = value;
  return cell;
}

function addToContainer(selector, element) {
  var container = document.querySelector(selector);
  container.appendChild(table);
}

var data = { key1: 1, key2: 2, key3: 3, key4: 4, key5: 5 };
createTableFromObject(data, '#content')
/* For demonstration purpose only */

td {
  margin: 5px;
  background: #ddd;
  border: 1px solid black;
  width: 50px;
  padding: 5px;
}
<div id='content' />

Comments

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.