Creating an HTML table from a JavaScript object

I am starting JavaScript and want to display an array of objects in HTML.

The data format is as follows:

[ {"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ] 

I want to use a list with three columns (identifier, name, relevance) to display them. And the identifier may increase from 1 automatically.

Can someone tell me how to write javascript code to display it?

Please give me some materials or examples to find out.

+7
source share
7 answers

explanation

You need to populate the table (or other DOMElement element) in HTML with your JavaScript, which runs dynamically after loading the page and receiving your JSON object.

You want to iterate over an object. The best way to do this is for loop and make sure that our cyclic variable remains valid for the length of our object (all its attributes).

The best way to get the length of a JSON object is to use myJSONObject.length : you select the keys myJSONObject and return their number.

You can access the values ​​stored in your JSON object as follows in a for loop (assuming the particular loop variable is called i ): myJSONObject[i].theAttributeIWantToGet


Price Formatting Breakdown

Now these prices should have the correct format, right? Therefore, we will check to see if any value attribute has less than 2 characters after . inside them. If they do, we will add another decimal 0 . We also add $ before writing the formatted value. Here is a breakdown of how this works:

  • obj[i].value.toString().substring(startIndex, length)

    • We want to check the length after . sign, so our startIndex will be the position of this point in our line.
    • obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
    • Now we need to set the length. We want to find the length of everything after the dot, so we take the length of the entire line just for security.
    • End result: obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2

      • This will return true or false. If this is true: there are less than 2 digits after the dot!
    • We add an if and the last zero:

    • if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";

Also: Why am I using innerHTML instead of appendChild() .


Decision

Jsfiddle

HTML

 <table> <tbody id="tbody"></tbody> </table> 

Json

 [{ "key": "apple", "value": 1.90 }, { "key": "berry", "value": 1.7 }, { "key": "banana", "value": 1.5 }, { "key": "cherry", "value": 1.2 }] 

Javascript

Note. In this case, the JSON object will be called obj .

 var tbody = document.getElementById('tbody'); for (var i = 0; i < obj.length; i++) { var tr = "<tr>"; /* Verification to add the last decimal 0 */ if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0"; /* Must not forget the $ sign */ tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>"; /* We add the table row to the table body */ tbody.innerHTML += tr; } 

Jsfiddle

+14
source

You can do something like this:

 var table = document.createElement("table"); //Add a header var header = document.createElement("tr"); var idHeaderCell = document.createElement("th"); var nameHeaderCell = document.createElement("th"); var relevanceHeaderCell = document.createElement("th"); header.appendChild(idHeaderCell); header.appendChild(nameHeaderCell); header.appendChild(relevanceHeaderCell); table.appendChild(header); //Add the rest of the data to the table for(var i = 0; i < data.length; i++) { var id = (i + 1); var name = data[i].key; var relevance = data[i].value; var tr = document.createElement("tr"); var idCell = document.createElement("td"); var nameCell = document.createElement("td"); var relevanceCell = document.createElement("td"); idCell.appendChild(document.createTextNode(id)); nameCell.appendChild(document.createTextNode(name)); relevanceCell.appendChild(document.createTextNode(relevance)); tr.appendChild(idCell); tr.appendChild(nameCell); tr.appendChild(relevanceCell); table.appendChild(tr); } 
+4
source

This can be done by a small and smart process:

 <table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center"> <thead> <tr> <th>Name</th> <th width="20%">Age</th> <th width="12%">Status</th> </tr> </thead> <tbody id="tableData"></tbody> </table> <script type="text/javascript"> var mainObj = [ { name: "Kapil", age: 21, status: "Active" }, { name: "John", age: 28, status: "Inactive" }, { name: "Deos", age: 18, status: "Active" } ]; var k = '<tbody>' for(i = 0;i < mainObj.length; i++){ k+= '<tr>'; k+= '<td>' + mainObj[i].name + '</td>'; k+= '<td>' + mainObj[i].age + '</td>'; k+= '<td>' + mainObj[i].status + '</td>'; k+= '</tr>'; } k+='</tbody>'; document.getElementById('tableData').innerHTML = k; </script> 
+4
source

Here is a function to build a table from any collection (array of objects)

Table creator

 const data=[ { name: "Kapil", age: 21, status: "Active" }, { name: "John", age: 28, status: "Inactive" }, { name: "Deos", age: 18, status: "Active", testing: 'Gooo!!' } ] const createTable=function(data){ const table = document.createElement("table"); const header = document.createElement("tr"); const keys=Object.keys(data[0]) console.log(keys) for(const key of keys){ const th=document.createElement("th"); th.appendChild(document.createTextNode(key)); header.appendChild(th); } table.appendChild(header); const len=data.length for(const row of data) { const tr = document.createElement("tr"); for(const key of keys){ const td = document.createElement("td"); const content=row[key] ||'' td.appendChild(document.createTextNode(content)); tr.appendChild(td); delete row[key] } /**** you can omit next cycle if all object have the same structor or if the first element of collection have all fields ****/ for(const key in row){ const th=document.createElement("th"); th.appendChild(document.createTextNode(key)) keys.push(key) header.appendChild(th); const td = document.createElement("td"); const content=row[key] ||'' td.appendChild(document.createTextNode(content)); tr.appendChild(td); } table.appendChild(tr); } return table 

}

+2
source

Iterate through the list and retrieve the data for each item this way (if your data is in data called var):

 for (var i = 0; i < data.length; i++) { var id = i + 1; var name = data[i].key; var relevance = data[i].value; } 

Then do something with the variables in each loop, print them out as you want.

+1
source

I'm not quite sure what you are asking for. The title of your post looks like you are looking for JSON.stringfy, as indicated in the previous answer, but apparently you are not doing this.

Are you trying to create and list HTML? Could you explain your need again? I doubt that you are trying to make it difficult, and I am sure that we can help you if you give a little more detail and the purpose of what you are trying to do.

I am going to guess that you are trying to display HMTL by going through a JSON object. Try this example using pure JavaScript:

 var fruits = JSON.parse('[{"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ]'); var tbl = document.createElement('table'); var thead = document.createElement("thead"); var tbody = document.createElement("tbody") var tr_head = document.createElement("tr"); var th_id = document.createElement("th"); var th_name = document.createElement("th"); var th_price = document.createElement("th"); th_id.textContent = "Id"; th_name.textContent = "Name"; th_price.textContent = "Price"; tr_head.appendChild(th_id); tr_head.appendChild(th_name); tr_head.appendChild(th_price); thead.appendChild(tr_head); for(var i = 0, j = fruits.length; i < j; i++) { var tr_body = document.createElement("tr"); var td_id = document.createElement("td"); var td_name = document.createElement("td"); var td_value = document.createElement("td"); td_id.textContent = i; td_name.textContent = fruits[i].key; td_value.textContent = fruits[i].value; tr_body.appendChild(td_id); tr_body.appendChild(td_name); tr_body.appendChild(td_value); tbody.appendChild(tr_body); } tbl.appendChild(thead); tbl.appendChild(tbody); console.log(tbl); 
+1
source

Maybe so:

 function obj2htmltable(obj) { var html = '<table>'; for (var key in obj) { var value = obj[key].toString(); html += '<tr><td>' + key + '</td><td>' + value + '</tr>'; } html += '</table>'; return html; } 

If the case is a nested structure (objects inside an object), obj2htmltable () can call itself recursively:

 function obj2htmltable(obj) { var html = '<table>'; for (var key in obj) { var item = obj[key]; var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString(); html += '<tr><td>' + key + '</td><td>' + value + '</tr>'; } html += '</table>'; return html; } 
0
source

Source: https://habr.com/ru/post/949580/


All Articles